[LeetCode] 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) {
        ListNode *head = l1;
        int flag = 0;
        ListNode *li1 = new ListNode(0);
        ListNode *li2 = new ListNode(0);
        li1->next = l1;
        li2->next = l2;

        while(li1->next!=NULL && li2->next!=NULL)
        {
            li1->next->val = li1->next->val+li2->next->val+flag;
            if(li1->next->val>9)
            {
                li1->next->val = li1->next->val-10;
                flag = 1;
            }
            else
            {
                flag = 0;
            }
            li1 = li1->next;
            li2 = li2->next;
        }
        while(li1->next != NULL && li2->next == NULL)
        {
            if(flag==1 && li1->next->val<9)
             {
                 ++li1->next->val;
                 flag = 0;
             }
             else if(flag==1 && li1->next->val==9)
             {
                 li1->next->val = 0;
                 flag = 1;
             }
            li1=li1->next;
        }
        while(li2->next != NULL && li1->next == NULL)
        {
            ListNode *p1;
             if(flag==1 && li2->next->val<9)
             {
                 p1 = new ListNode(li2->next->val+1);
                 flag = 0;
             }
             else if(flag==1 && li2->next->val==9)
             {
                 p1 = new ListNode(0); 
                 flag = 1;
             }
             else
             {
               p1 = new ListNode(li2->next->val);
             }
             li1->next =p1;
            li1 = li1->next;  
            li2 = li2->next;
        }
        if(flag == 1)
        {
            ListNode *p = new ListNode(1);
            li1->next = p;
            
        }
        return head;
    }
    
};

 

posted @ 2014-06-23 15:52  Xylophone  Views(113)  Comments(0Edit  收藏  举报