【LeetCode】Add Two Numbers

来源:互联网 发布:528雾化器口感数据 编辑:程序博客网 时间:2024/06/05 16:05

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

思路:很简单,主要注意要是有进一位时要特别加一个链结点。我在这块做了很久,才找到问题。

ListNode *xx=new ListNode(rize);
代码如下:



/** * 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) {        if(l1==NULL&&l2==NULL)return NULL;        if(l1==NULL)return l2;        if(l2==NULL)return l1;        ListNode *head,*rel;        int tmp=0,rize=0;        head=l1;        rel=head;        tmp=(l1->val+l2->val+rize);        rize=tmp/10;        rel->val=tmp%10;        while((l1->next!=NULL)&&(l2->next!=NULL)){            l1=l1->next;            l2=l2->next;            rel=rel->next;            #ifdef DE_BUG            cout<<"1(l1->next!=NULL)&&(l2->next!=NULL)"<<endl;            #endif                        tmp=(l1->val+l2->val+rize);            rize=tmp/10;            rel->val=tmp%10;        }        if(l1->next==NULL&&l2->next==NULL){    if(rize!=0){            ListNode *xx=new ListNode(rize);            rel->next=xx;            //rel->next->val=rize;                        #ifdef DE_BUG            cout<<"rize="<<rel->next->val<<endl;            cout<<"4rize!=0"<<endl;            #endif                        //rel=rel->next;        }        return head;    }        if(l1->next==NULL){            rel->next=l2->next;            while(l2->next!=NULL){                rel=rel->next;                l2=l2->next;                                tmp=(l2->val+rize);                rize=tmp/10;                rel->val=tmp%10;                                #ifdef DE_BUG            cout<<"2(l1->next!=NULL)&&(l2->next=NULL)"<<endl;            #endif            }        }        else if(l2->next==NULL){            rel->next=l1->next;            while(l1->next!=NULL){                rel=rel->next;                l1=l1->next;                                tmp=(l1->val+rize);                rize=tmp/10;                rel->val=tmp%10;                                #ifdef DE_BUG            cout<<"3(l1->next=NULL)&&(l2->next==NULL)"<<endl;            #endif            }        }        if(rize!=0){            ListNode *xx=new ListNode(rize);            rel->next=xx;            //rel->next->val=rize;                        #ifdef DE_BUG            cout<<"rize="<<rel->next->val<<endl;            cout<<"4rize!=0"<<endl;            #endif                        //rel=rel->next;        }        //rel->next=NULL;        return head;    }};


0 0