Add Two Numbers

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:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

 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<Integer> list1 = new Stack<>();
12         while(l1 != null) {
13             list1.push(l1.val);
14             l1 = l1.next;
15         }
16         
17         Stack<Integer> list2 = new Stack<>();
18         while(l2 != null) {
19             list2.push(l2.val);
20             l2 = l2.next;
21         }
22         
23         ListNode current = new ListNode(-1);
24         int carry = 0;
25         while(!list1.isEmpty() || !list2.isEmpty() || carry == 1) {
26             int val1 = 0, val2 = 0;
27             if (!list1.isEmpty()) {
28                 val1 = list1.peek();
29                 list1.pop();
30             }
31             if (!list2.isEmpty()) {
32                 val2 = list2.peek();
33                 list2.pop();
34             }
35             
36             int tempVal = val1 + val2 + carry;
37             carry = tempVal / 10;
38             
39             if (current.val == -1) {
40                 current.val = tempVal % 10;
41             } else {
42                 ListNode temp = new ListNode(tempVal % 10);
43                 temp.next = current;
44                 current = temp;
45             }
46         }
47         return current;
48     }
49 }

 

posted @ 2017-02-24 19:29  amazingzoe  阅读(162)  评论(0编辑  收藏  举报