兩數相加 II
給你兩個 非空 鏈表來代表兩個非負整數。數字最高位位於鏈表開始位置。它們的每個節點只存儲一位數字。將這兩數相加會返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 8 -> 0 -> 7
思路
1.要求從鏈表尾爲準開始加,可以反轉鏈表或者使用棧先進後出的原理,題目中不對鏈表進行修改,所以引入兩個輔助棧裝兩個鏈表數據,然後出棧相加,對相加的數做一個%10的操作,方便進位。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
//將兩個鏈表分別放入兩個輔助棧中
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int last = 0;
ListNode head = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || last > 0) {
//遍歷棧,對應相加
last += stack1.isEmpty() ? 0 : stack1.pop();
last += stack2.isEmpty() ? 0 : stack2.pop();
//計算當前節點值,使用相加和%10,得到個位數
ListNode node = new ListNode(last % 10);
node.next = head;
head = node;
//得到這一位的進位
last = last / 10;
}
return head;
}