样例 给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
总耗时: 241 ms 49% 数据通过测试. 输入 1->1->1->1->1->null 9->8->8->8->8->null 输出 0->0->0->0->0->0->null 期望答案 0->0->0->0->0->1->null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ ListNode *addLists(ListNode *l1, ListNode *l2) { if(l1==NULL) { return l2; } if(l2==NULL) { return l1; } int jw=0; int temp=0; ListNode*dummy=new ListNode(0); ListNode*p=dummy; while(l1!=NULL&&l2!=NULL) { temp=l1->val+l2->val+jw; jw=temp/10; temp=temp; p->next=new ListNode(temp); p=p->next; l1=l1->next; l2=l2->next; } while(l1!=NULL) { temp=l1->val+jw; jw=temp/10; temp=temp; p->next=new ListNode(temp); p=p->next; l1=l1->next; } while(l2!=NULL) { temp=l2->val+jw; jw=temp/10; temp=temp; p->next=new ListNode(temp); p=p->next; l2=l2->next; } if(jw!=0) { p->next=new ListNode(jw); } return dummy->next; // write your code here } };