Description:
假定用一個連結清單表示兩個數,其中每個節點僅包含一個數字。假設這兩個數的數字順序排列,請設計一種方法将兩個數相加,并将其結果表現為連結清單的形式。
Explanation:
給出 6->1->7 + 2->9->5。即,617 + 295。
傳回 9->1->2。即,912 。
Solution:
利用棧的先進後出,記錄兩個連結清單的節點值。然後計算對應位置的兩個數字之和,如果有進位,指派給flag并帶入下一個計算。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
// write your code here
Stack<Integer> temp1 = reverseNode(l1);
Stack<Integer> temp2 = reverseNode(l2);
ListNode point = new ListNode(0);
int flag = 0;
while((!temp1.isEmpty()) && (!temp2.isEmpty())){
int value = temp1.pop() + temp2.pop() + flag;
flag = value/10;
value = value%10;
ListNode cur = new ListNode(value);
cur.next = point.next;
point.next = cur;
}
while(!temp1.isEmpty()){
int value = temp1.pop() + flag;
flag = value/10;
value = value%10;
ListNode cur = new ListNode(value);
cur.next = point.next;
point.next = cur;
}
while(!temp2.isEmpty()){
int value = temp2.pop() + flag;
flag = value/10;
value = value%10;
ListNode cur = new ListNode(value);
cur.next = point.next;
point.next = cur;
}
if(flag == 1){
ListNode cur = new ListNode(1);
cur.next = point.next;
point.next = cur;
}
return point.next;
}
public Stack<Integer> reverseNode(ListNode temp){
Stack<Integer> record = new Stack<Integer>();
while(temp != null){
record.push(temp.val);
temp = temp.next;
}
return record;
}
}