Add Two Numbers

PROBLEM :

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

--------------------------------------------------------------------------------
SIMPLE C++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
 
    int r=0,no;
    struct ListNode *sum=NULL,*t,*temp ;
    while(l1!=NULL&&l2!=NULL)
    {
        temp=(struct ListNode*)malloc(sizeof(struct ListNode)) ;
        no=l1->val+l2->val+r ;
        temp->val=no%10 ;
        r=no/10 ;
        temp->next=NULL ;
     
        if(sum==NULL)
        {
            sum=temp ;  
        }
        else
        {
            t=sum ;
            while(t->next!=NULL)
            t=t->next ;
            t->next=temp ;
        }
     
        l1=l1->next ;
        l2=l2->next ;
    }
 
    while(l1!=NULL)
    {
        temp=(struct ListNode*)malloc(sizeof(struct ListNode)) ;
        no=l1->val+r ;
        temp->val=no%10 ;
        r=no/10 ;
        temp->next=NULL ;
     
        if(sum==NULL)
        {
            sum=temp ;  
        }
        else
        {
            t=sum ;
            while(t->next!=NULL)
            t=t->next ;
            t->next=temp ;
        }
     
        l1=l1->next ;
    }
 
    while(l2!=NULL)
    {
        temp=(struct ListNode*)malloc(sizeof(struct ListNode)) ;
        no=l2->val+r ;
        temp->val=no%10 ;
        r=no/10 ;
        temp->next=NULL ;
     
        if(sum==NULL)
        {
            sum=temp ;  
        }
        else
        {
            t=sum ;
            while(t->next!=NULL)
            t=t->next ;
            t->next=temp ;
        }
     
        l2=l2->next ;  
    }
 
    if(r!=0)
    {
        temp=(struct ListNode*)malloc(sizeof(struct ListNode)) ;
        temp->val=r ;
        temp->next=NULL ;
     
        t=sum ;
        while(t->next!=NULL)
        t=t->next ;
        t->next=temp ;
    }
 
    return sum ;
}

-----------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )