Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

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

注意:1.得第一个数字位于链表的开头.2.进位 3.  1->3->null 9->6->null 的情况 答案为 0->0->1->null

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;      
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param l1: the first list
15      * @param l2: the second list
16      * @return: the sum list of l1 and l2 
17      */
18     public ListNode addLists(ListNode l1, ListNode l2) {
19         if (l1 == null && l2 == null) {
20             return null;
21         }
22         if (l1 == null) {
23             return l2;
24         }
25         if (l2 == null) {
26             return l1;
27         }
28         ListNode dummy = new ListNode(0);
29         ListNode head = dummy;
30         boolean carry = false;
31         while (l1 != null && l2 != null) {
32             int value = 0;
33             if (carry) {
34                 value = l1.val + l2.val + 1;
35                 carry = false;
36             } else {
37                 value = l1.val + l2.val;
38             }
39             if (value >= 10) {
40                 carry = true;
41                 value = value - 10;
42             } 
43             head.next = new ListNode(value);
44             head = head.next;
45             l1 = l1.next;
46             l2 = l2.next;
47         }
48         if (l1 == null && l2 == null && carry) {
49             head.next = new ListNode(1);
50             head = head.next;
51         }
52         while (l1 != null) {
53             int val = l1.val;
54             if (carry) {
55                 carry = false;
56                 val++;
57             }
58             head.next = new ListNode(val);
59             head = head.next;
60             l1 = l1.next;
61         }
62         while (l2 != null) {
63             int val = l2.val;
64             if (carry) {
65                 carry = false;
66                 val++;
67             }
68             head.next = new ListNode(val);
69             head = head.next;
70             l2 = l2.next;
71         }
72         head.next = null;
73         return dummy.next;
74     }
75 }

 

  

posted @ 2016-04-15 09:22  YuriFLAG  阅读(156)  评论(0)    收藏  举报