Wednesday, May 16, 2012

Add two Number

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

Below is the working c code
 
#include<stdio.h>
#include<stdlib.h>
struct node
{
        unsigned int val;
        struct node * next;
};
typedef struct node * nodeptr;
void insert(nodeptr * head,unsigned int item)
{
        nodeptr temp = (nodeptr) malloc(sizeof(nodeptr));
        temp->val = item;
        temp->next = *head;
        *head = temp;
}
void print(nodeptr head)
{
        while (head)
        {
                printf("%d ",head->val);
                head=head->next;
        }
        printf("\n");
}
nodeptr add(nodeptr head1,nodeptr head2)
{
        nodeptr temp=NULL;
        unsigned int sum=0,carry = 0;
        while(head1!=NULL && head2!=NULL)
        {
                sum = head1->val + head2->val;
                insert(&temp,(sum%10)+carry);
                carry = sum/10;
                head1=head1->next;
                head2=head2->next;
        }
        while(head1)
        {
                insert(&temp,head1->val+carry);
                carry = 0;
                head1=head1->next;
        }
        while(head2)
        {
                 insert(&temp,head2->val+carry);
                 carry = 0;
                 head2=head2->next;
        }
        if(carry!=0)
                insert(&temp,carry);
        return temp;
}
void reverse(nodeptr *head)
{
       nodeptr h1,h2;
       h1=*head;
       h2=h1->next;
       h1->next=NULL;
       *head=h1;
       while(h2)
       {
                h1=h2->next;
                h2->next=*head;
                *head=h2;
                h2=h1;
       }        
}
int main()
{
        nodeptr root = NULL,root1=NULL,result=NULL;
        insert(&root,2);
        insert(&root,3);
        insert(&root1,9);
        insert(&root1,8);
        result=add(root,root1);
        reverse(&result);
        print(root);
        print(root1);
        print(result);
        return 0;
}

No comments:

Post a Comment