[leetcode]2. Add Two Numbers

 2. Add Two Numbers

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

 

 

/**
 * 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) {
        int take=0;     //represent the carry
        if(l1==NULL||l2==NULL)
            return l1?l1:l2;
        ListNode* p1=l1,*p2=l2;
        while(p1->next!=NULL&&p2->next!=NULL){
            int tmp=p1->val+p2->val+take;
            p1->val=tmp%10;
            take=tmp/10;
            p1=p1->next;
            p2=p2->next;
        }
        
        if(p1->next==NULL){
            int tmp=p1->val+p2->val+take;
            p1->val=tmp%10;
            take=tmp/10;
            if(p2->next==NULL)
            {
                if(take==0)
                    return l1;
                else
                    p1->next=new ListNode(take);
            }
            else{
                if(take==0){
                    p1->next=p2->next;
                    return l1;
                }
                else{
                    p1->next=p2->next;
                    p2=p2->next;
                    while(p2->next!=NULL&&take!=0){
                        int tmp=p2->val+take;
                        p2->val=tmp%10;
                        take=tmp/10;
                        p2=p2->next;
                    }
                    if(p2->next==NULL){
                        if((take+p2->val)>=10){
                            
                            p2->next= new ListNode((take+p2->val)/10);
                            p2->val=(take+p2->val)%10;
                        }
                        else p2->val+=take;
                }
            }
        }
        }
        else{
            int tmp=p1->val+p2->val+take;
            p1->val=tmp%10;
            take=tmp/10;
            p1=p1->next;
            while(p1->next!=NULL&&take!=0){
                int tmp=p1->val+take;
                p1->val=tmp%10;
                take=tmp/10;
                p1=p1->next;
            }
            if(p1->next==NULL){
                if((take+p1->val)>=10){
                    
                    p1->next=new ListNode((take+p1->val)/10);
                    p1->val=(take+p1->val)%10;
                }
                else p1->val+=take;
            }
        }
        return l1;
        
        
    }
};

 

posted @ 2016-07-08 02:06  0giant  阅读(150)  评论(0编辑  收藏  举报