Tuesday 4 October 2016

Add Two Numbers (LeetCode)

Problem: 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. 

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

No comments:

Post a Comment