LeetCode - Add Two Numbers

 

 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     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         ListNode *addNum = new ListNode(0);// head-node for explicity
15         ListNode *p1 = l1;
16         ListNode *p2 = l2;
17         ListNode *padd = addNum;
18         int total;
19         int flag = 0;
20         
21         //类似于归并
22         while(p1!=NULL && p2!=NULL)
23         {
24             total = p1->val + p2->val + flag;
25             flag = total / 10;
26             total = total % 10;
27             padd->next = new ListNode(total);
28             padd = padd->next;
29             p1 = p1->next;
30             p2 = p2->next;
31         }
32         
33         while(p1!=NULL)
34         {
35             total = p1->val + flag;
36             flag = total / 10;
37             total = total % 10;
38             padd->next = new ListNode(total);
39             padd = padd->next;
40             p1 = p1->next;
41         }
42         
43         while(p2!=NULL)
44         {
45             total = p2->val + flag;
46             flag = total / 10;
47             total = total % 10;
48             padd->next = new ListNode(total);
49             padd = padd->next;
50             p2 = p2->next;
51         }
52         
53         // 易忘最高升位!
54         if(flag!=0)
55         {
56             padd->next = new ListNode(flag);
57         }
58         
59         padd = addNum->next;
60         delete []addNum; // free the head-node!!!
61         
62         return padd;
63     }
64 };

 

posted on 2013-05-03 15:29  highstar88  阅读(126)  评论(0编辑  收藏  举报

导航