leetcode445 Add Two Numbers II java

Description You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
【leetcode445 Add Two Numbers II java】Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
解法 用栈可以很方便解决。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack stack1 = new Stack<>(); Stack stack2 = new Stack<>(); while(l1 != null) { stack1.push(l1.val); l1 = l1.next; } while(l2 != null) { stack2.push(l2.val); l2 = l2.next; } ListNode result = new ListNode(0); int carry = 0; while(!(stack1.isEmpty() && stack2.isEmpty())) { int num1 = stack1.isEmpty() ? 0 : stack1.pop(); int num2 = stack2.isEmpty() ? 0 : stack2.pop(); result.val = (num1 + num2 + carry) % 10; carry = (num1 + num2 + carry) / 10; ListNode head = new ListNode(carry); head.next = result; result = head; } return result.val == 0 ? result.next : result; }

    推荐阅读