Lintcode: Add Two Numbers

C++

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     /**
12      * @param l1: the first list
13      * @param l2: the second list
14      * @return: the sum list of l1 and l2 
15      */
16     ListNode *addLists(ListNode *l1, ListNode *l2) {
17         // write your code here
18         if (l1 == NULL) {
19             return l2;
20         }
21         if (l2 == NULL) {
22             return l1;
23         }
24         ListNode *ptr1 = l1, *ptr2 = l2;
25         ListNode *result = new ListNode(-1);
26         ListNode *pre = result;
27         int carry = 0, val = 0;
28         while (ptr1 != NULL || ptr2 != NULL) {
29             int val1 = ptr1 == NULL?0:ptr1->val;
30             int val2 = ptr2 == NULL?0:ptr2->val;
31             int sum = val1 + val2 + carry;
32             val = sum;
33             carry = sum/10;
34             pre->next = new ListNode(val);
35             pre = pre->next;
36             if (ptr1!=NULL)
37             {
38                 ptr1 = ptr1->next;
39             }
40             if (ptr2!=NULL) 
41             {
42                 ptr2 = ptr2->next;
43             }
44         }
45         if (carry == 1) {
46             pre->next = new ListNode(1);
47         }
48         return result->next;
49     }
50 };

 

posted @ 2015-11-26 20:15  ZH奶酪  阅读(230)  评论(0编辑  收藏  举报