Narcissus's blog Stay Follish, Stay Hungry

2. Add Two Numbers

2018-05-08
Narcissus

2. Add Two Numbers

/**
 * 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 carray=0,idx=1;
        ListNode*temp1=l1,*temp2=l2,*sum=NULL,*temp3=NULL;
        while(temp1!=NULL||temp2!=NULL)
        {
            int temp_sum=0;
            if(temp1!=NULL&&temp2!=NULL)
            {
                temp_sum=temp1->val+temp2->val+carray;
                temp1=temp1->next;
                temp2=temp2->next;
            }
            else if(temp1!=NULL)
            {
                temp_sum=temp1->val+carray;
                temp1=temp1->next;
            }
            else 
            {
                temp_sum=temp2->val+carray;
                temp2=temp2->next;
            }
            
            if(temp_sum>9)
            {
                carray=1;
                temp_sum%=10;
            }
            else
            {
                carray=0;
            }
            if(sum==NULL)
            {
                sum=new ListNode(temp_sum);
                temp3=sum;
            }
            else
            {
                temp3->next=new ListNode(temp_sum);
                temp3=temp3->next;
            }

        }
        
        if(carray!=0)temp3->next=new ListNode(1);
        return sum;
    }
};

Comments

Content