You are given two linked lists representing two non-negative numbers. 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: Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
The key of this problem is to think of using Stack
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 Stack<ListNode> st1 = new Stack<ListNode>(); 12 Stack<ListNode> st2 = new Stack<ListNode>(); 13 while (l1 != null) { 14 st1.push(l1); 15 l1 = l1.next; 16 } 17 while (l2 != null) { 18 st2.push(l2); 19 l2 = l2.next; 20 } 21 ListNode dummy = new ListNode(-1); 22 int carry = 0; 23 while (st1.size()!=0 || st2.size()!=0 || carry!=0) { 24 int sum = 0; 25 if (st1.size() != 0) sum += st1.pop().val; 26 if (st2.size() != 0) sum += st2.pop().val; 27 if (carry != 0) sum += carry; 28 ListNode newNode = new ListNode(sum%10); 29 newNode.next = dummy.next; 30 dummy.next = newNode; 31 carry = sum / 10; 32 } 33 return dummy.next; 34 } 35 }