您的位置:首页 > 其它

LeetCode *** 2. Add Two Numbers

2016-04-05 11:47 267 查看
题目:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

分析:
一位一位的加,注意要保留进位,同时l1与l2可能位数不一样,也需要注意,大概就这样吧。我RE了很久,我也不知道为啥。。。我到现在都没明白。。我cpp还是忘得差不多了。。心塞。。。

代码:
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

ListNode *res,*restmp,*l1tmp,*l2tmp;
l1tmp=l1;l2tmp=l2;
int CA=0;
res=new ListNode(0);
restmp=res;

while(l1tmp!=NULL&&l2tmp!=NULL){
int tmp=l1tmp->val+l2tmp->val+CA;
CA=tmp/10;

restmp->next=new ListNode(tmp%10);
restmp=restmp->next;
//    if(l1->next!=NULL)
l1tmp=l1tmp->next;
//    if(l2->next!=NULL)
l2tmp=l2tmp->next;
}

while(l1tmp!=NULL&&l2tmp==NULL){
int tmp=l1tmp->val+CA;
CA=tmp/10;

restmp->next=new ListNode(tmp%10);
restmp=restmp->next;

l1tmp=l1tmp->next;
}

while(l1tmp==NULL&&l2tmp!=NULL){
int tmp=l2tmp->val+CA;
CA=tmp/10;

restmp->next=new ListNode(tmp%10);
restmp=restmp->next;

l2tmp=l2tmp->next;
}

if(CA!=0){

restmp->next=new ListNode(CA);
restmp=restmp->next;

}

return res->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: