1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode();
Stack<Integer> stackA = new Stack<>(); Stack<Integer> stackB = new Stack<>();
while (l1 != null) { stackA.push(l1.val); l1 = l1.next; } while (l2 != null) { stackB.push(l2.val); l2 = l2.next; }
int carry = 0; while (!stackA.isEmpty() || !stackB.isEmpty() || carry != 0) { int sum = carry; if (!stackA.isEmpty()) { sum += stackA.pop(); } if (!stackB.isEmpty()) { sum += stackB.pop(); }
ListNode next = dummyHead.next; dummyHead.next = new ListNode(sum % 10); dummyHead.next.next = next; carry = sum / 10; }
return dummyHead.next; } }
|
References
445. Add Two Numbers II
剑指 Offer II 025. 链表中的两数相加