leetcode 2 Add Two Numbers

主要注意别手误,每个if else情况写全。

 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         ListNode *ret = new ListNode(0);
13         ListNode *tl, *node = ret;
14         int tt = 0;
15         while(true){
16             if(l1){
17                 if(l2){
18                     int tmp = l1->val+l2->val+tt;
19                     if(tmp>=10) {
20                         node->val = tmp-10;
21                         tt = 1;
22                     }else{
23                         node->val = tmp;
24                         tt = 0;
25                     }
26                     l1 = l1->next;
27                     l2 = l2->next;
28                     node->next = new ListNode(0);
29                     tl = node;
30                     node = node->next;
31                 }else{
32                     while(l1){
33                         int tmp = l1->val+tt;
34                         if(tmp>=10) {
35                             node->val = tmp-10;
36                             tt = 1;
37                         }else{
38                             node->val = tmp;
39                             tt = 0;
40                         }
41                         l1 = l1->next;
42                         node->next = new ListNode(0);
43                         tl = node;
44                         node = node->next;
45                     }
46                     break;
47                 }
48             }else if(l2){
49                 while(l2){
50                     int tmp = l2->val+tt;
51                     if(tmp>=10) {
52                         node->val = tmp-10;
53                         tt = 1;
54                     }else{
55                         node->val = tmp;
56                         tt = 0;
57                     }
58                     l2 = l2->next;
59                     node->next = new ListNode(0);
60                     tl = node;
61                     node = node->next;
62                 }
63                 break;
64             }else{
65                 break;
66             }
67         }
68 
69         if(tt){
70             node->val = 1;
71         }else{
72             delete node;
73             tl->next = NULL;
74         }
75 
76         return ret;
77     }
78 };
View Code

 

posted @ 2019-04-13 23:33  jiu~  阅读(142)  评论(0编辑  收藏  举报