Sunday, April 13, 2014

[LeetCode] Add Two Numbers

Problem Statement (link):
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
Analysis:
This problem is quite straight-forward: we traverse the linked list and add corresponding node's values from two given lists to form a new list.

There are several corner cases to consider:
1) Two lists may have different length: we need to consider the extra nodes from longer list.
2) Carry: we need to remember the carry - 1 or 0 - from previous node(s). If it's end of the list and there's a carry, we need to create a new node with value 1.

Code:
/**
 * 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) {
        if (l1==NULL && l2==NULL) return NULL;
        ListNode* h1=l1, *h2=l2;
        // add first node
        ListNode* l3=new ListNode((h1->val+h2->val)%10);
        int carry=(h1->val+h2->val>=10)?1:0;
        h1=h1->next; h2=h2->next;
        ListNode* prev=l3;
        // traverse
        while(h1!=NULL && h2!=NULL) {
            ListNode* tmp=new ListNode((h1->val+h2->val+((carry==1)?1:0))%10);
            carry=(h1->val+h2->val+((carry==1)?1:0)>=10)?1:0;
            prev->next=tmp;
            prev=prev->next;
            h1=h1->next;
            h2=h2->next;
        }
        // If list 1 is longer than list 2
        if (h1!=NULL) {
            while(h1!=NULL) {
                ListNode* tmp=new ListNode((h1->val+((carry==1)?1:0))%10);
                carry=(h1->val+((carry==1)?1:0)>=10)?1:0;
                prev->next=tmp;
                prev=prev->next;
                h1=h1->next;
            }
        }
        // If list 2 is longer than list 1
        if (h2!=NULL) {
            while(h2!=NULL) {
                ListNode* tmp=new ListNode((h2->val+((carry==1)?1:0))%10);
                carry=(h2->val+((carry==1)?1:0)>=10)?1:0;
                prev->next=tmp;
                prev=prev->next;
                h2=h2->next;
            }
        }
        // If there's carry at the last node - create a new node->val=1
        if (h1==NULL && h2==NULL && carry==1) {
            ListNode* tmp=new ListNode(1);
            prev->next=tmp;
        }
        return l3;
    }
};

No comments:

Post a Comment