給你兩個 非空 鏈表來代表兩個非負整數。數字最高位位于鏈表開始位置。它們的每個節點只存儲一位數字。將這兩數相加會返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
進階:
如果輸入鏈表不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。
示例:
輸入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 8 -> 0 -> 7
思路:放入棧中再相加。
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {Stack<Integer> s1 = new Stack<>();Stack<Integer> s2 = new Stack<>();while(l1 != null) {s1.push(l1.val);l1 = l1.next;}while(l2 != null) {s2.push(l2.val);l2 = l2.next;}ListNode res = null;int c = 0;while(!s1.isEmpty() || !s2.isEmpty() || c > 0) {int sum = (s1.isEmpty() ? 0 : s1.pop()) +(s2.isEmpty() ? 0 : s2.pop()) + c;ListNode n = new ListNode(sum % 10);c = sum / 10;n.next = res;res = n;}return res;}
}
?