Leetcode002 Add Two Numbers

//Memory Limit Exceeded

/**
 * 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 carry=0,sum;
        ListNode* tail=NULL; 
        ListNode* head=tail;
        while(l1!=NULL && l2!= NULL)
        {
            sum=l1->val+l2->val+carry;
            tail=new ListNode(sum%10);
            tail=tail->next;
            carry=sum/10;
        }
        if(l1==NULL)l1=l2;
        while(l1!=NULL)
        {
            sum=l1->val+carry;
            tail=new ListNode(sum%10);
            tail=tail->next;
            carry=sum/10;
        }
        if(carry!=0)
        {
            tail=new ListNode(carry);
            tail=tail->next;
        }
        return head;
    }
};


/* the reason of it cann`t accepeted in the first submit :
 * the wrong use of the last longlist which is point to null which cann`t be assigned by the address returned by new
 * the program upside may has  the same wrong in tail about the last point to NULL.

/**
 * 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* longlist=l1;
        ListNode* shortlist=l2;
        while(l1 != NULL && l2 != NULL){l1=l1->next;l2=l2->next;}
        if (l1 == NULL){ ListNode* tmp=longlist;longlist=shortlist; shortlist=tmp;}
        int carry=0,sum;
        ListNode* longhead=longlist;
        while(shortlist != NULL && longlist != NULL )
        {
            sum=longlist->val+shortlist->val+carry;
            longlist->val=sum%10;
            carry=sum/10;
            longlist=longlist->next;
            shortlist=shortlist->next;
            
        }
        while(longlist!=NULL)
        {
            sum=longlist->val+carry;
            longlist->val=sum%10;
            carry=sum/10;
            longlist=longlist->next;
            //if(carry==0)break;
        }
        if(carry!=0)
        {
            for(longlist=longhead;longlist->next!=NULL;longlist=longlist->next);/*be careful foe the last longlist which had pointed to NULL*/
            longlist->next=new ListNode(carry);
        }
        /*while(longhead!=NULL)
        {
            cout<<longhead->val<<' ';
            longhead=longhead->next;
        }
        */
        return longhead;
    }
};

 

posted @ 2016-09-07 15:31  zeroArn  阅读(134)  评论(0)    收藏  举报