Web Toolbar by Wibiya

Pages

Tuesday, April 19, 2011

Given two numbers represented by linked lists with each node containing a single digit. Add them and return the list containing the resulting number.

Solution #1: Traverse both the lists adding their node's digit and storing the sum in the resulting list till one of the lists ends. Continue from the remaining list and add rest of its nodes to the resulting list. Here is the code,

Example:
list 1: 4 -> 5 -> 6
list 2: 7 -> 8 -> 9
result: 1 -> 4 -> 6 > 1

node* addLists(node* lptr1, node* lptr2)
{
    node* list = NULL;
    node* prev = NULL;
    node* remaining = NULL;
    int carry=0;
    int sum=0;

    while((lptr1 != NULL) && (lptr2!= NULL))
    {
        sum = 0;

        node* temp = (node*)malloc(sizeof(node));
        sum = lptr1->data + lptr2->data + carry;
        carry=0;

        if(sum >= 10)
            carry = 1;

        sum = sum%10;
        temp->data = sum;
        temp->next = NULL;

        if(list == NULL)
        {
            list = temp;
            prev = temp;
        }
        else
        {
            prev->next = temp;
        }

        prev = temp;
        
        lptr1 = lptr1->next;
        lptr2 = lptr2->next;
    }

    remaining = (lptr1 != NULL)?lptr1:lptr2;

    while(remaining != NULL)
    {
        node* temp = (node*)malloc(sizeof(node));
        temp->data = remaining->data + carry;
        carry = 0;
        temp->next = NULL;

        prev->next = temp;

        prev = temp;
        remaining = remaining->next;
    }

    return list;
}

1 comment:

Unknown said...

Hi,

In your logic, i don't see the "list" getting updated. I believe we should be returning the prev instead of list here. Please check this.