題目描述:你有兩個用鏈表代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序,使得第一個數字位於鏈表的開頭。寫出一個函數將兩個整數相加,用鏈表形式返回和。
樣例
給出兩個鏈表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
注意點:如果兩個數相加結束之後,進位不爲零,此時表示,結果值比原來的鏈表要更長一位。此時需要單獨處理,增加一個節點。Wrong Answer
總耗時: 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
}
};