problem 2: 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  
10  void addtolist(int val, int& add, ListNode*&head, ListNode*&pre)
11  {
12      int sum = val + add;
13      if (sum >= 10){
14          add = 1;
15          sum -= 10;
16          
17      }
18      else {
19          add = 0;
20      }
21      ListNode *node = new ListNode(sum);
22      if (!head){
23          head = node;
24      }
25      if (NULL != pre) {
26          pre->next = node;
27      }
28      pre = node;
29  }
30  
31 class Solution {
32 public:
33     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
34         if (!l1 && !l2){
35             return NULL;
36         }
37         ListNode *head = NULL;
38         ListNode *pre = NULL;
39         int add = 0;
40         while (l1 != NULL && l2 != NULL){
41             addtolist(l1->val + l2->val, add, head, pre);
42             l1 = l1->next;
43             l2 = l2->next;
44         }
45         while (l1){
46            addtolist(l1->val, add, head, pre);
47            l1 = l1->next;
48         }
49         while (l2){
50            addtolist(l2->val, add, head, pre);
51             l2 = l2->next;
52         }
53         if (add){
54             addtolist(0, add, head, pre);
55         }
56         return head;
57     }
58 };

 

posted @ 2016-09-06 21:29  nosaferyao  阅读(166)  评论(0编辑  收藏  举报