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 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
21     {
22         if(l1==NULL)
23             return l2;
24         if(l2==NULL)
25             return l1;
26         int flag=0;
27         ListNode *head=new ListNode(0);
28         ListNode *res=head;
29         while(l1||l2)
30         {
31             int vl1,vl2;
32             vl1= l1==NULL? 0:l1->val;
33             vl2= l2==NULL? 0:l2->val;
34             int sum=vl1+vl2+flag;
35             flag=sum/10;
36             head->next=new ListNode(sum%10);
37             head=head->next;
38             if(l1)
39                 l1=l1->next;
40             if(l2)
41                 l2=l2->next;
42         }
43         if(flag)
44             head->next=new ListNode(flag);
45         return res->next;   
46     }
47 };

使用新建链表的方法较为简单

posted on 2018-07-03 10:41  高数考了59  阅读(148)  评论(0)    收藏  举报