/*Given two numbers, where each digit is represented as a node of a linked list, add those numbers*/
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int cntList1=0;
int cntList2=0;
struct node
{
int data;
struct node *next;
};
/*Utility function to create node*/
void createNode(struct node** head, int data)
{
struct node *temp = (struct node *)malloc(sizeof(struct node *));
temp->data = data;
temp->next=(*head);
(*head) = temp;
}
/*Utility function to reverse list*/
void reverseList(struct node** head,int *cnt)
{
if(!head)
return;
else
{
struct node *prev,*curr,*next;
prev= NULL;
curr=(*head);
while(curr!=NULL)
{
next = curr->next;
curr->next=prev;
prev=curr;
curr=next;
(*cnt)++;
}
(*head) = prev;
}
}
/*Utility function to print list*/
void printList(struct node *head)
{
int i=0;
while(head)
{
printf("element %d : %d\n",i++,head->data);
head=head->next;
};
}
/*Utility function to calculate sum*/
void printSum(struct node* head1, struct node* head2)
{
reverseList(&head1,&cntList1);
//printf("Reversed List 1 is:\n");
//printList(head1);
reverseList(&head2,&cntList2);
//printf("Reversed List 2 is:\n");
//printList(head2);
int sum=0,power=0,result=0;
int carry=0;
struct node* root1 = head1;
struct node* root2 = head2;
while(cntList1 > 0 || cntList2 > 0)
{
if(root1 && root2)
{
sum = root1->data + root2->data + carry ;
root1 = root1->next;
root2 = root2->next;
cntList1--;
cntList2--;
}
else if(root1)
{
sum = root1->data + carry ;
root1 = root1->next;
cntList1--;
}
else if(root2)
{
sum = root2->data + carry ;
root2 = root2->next;
cntList2--;
}
carry = sum/10;
sum = sum % 10;
result = result + sum * pow(10,power);
power++;
//printf("cntList1 : %d cntList2 : %d\n",cntList1,cntList2);
//printf("sum: %d carry: %d result: %d\n",sum,carry,result);
};
if(carry)
result = result + carry * pow(10,power++);
printf("Sum is %d\n",result);
}
/*Helper function to create linked lists*/
int main()
{
struct node* head1 = NULL;
createNode(&head1,4);
createNode(&head1,2);
createNode(&head1,6);
createNode(&head1,1);
createNode(&head1,4);
//printf("List 1 is:\n");
//printList(head1);
struct node* head2 = NULL;
createNode(&head2,5);
createNode(&head2,7);
createNode(&head2,8);
createNode(&head2,0);
createNode(&head2,9);
//printf("List 2 is:\n");
//printList(head2);
printSum(head1,head2);
return 0;
}
Thursday, 10 July 2014
Problem Statement: Given two numbers, where each digit is represented as a node of a linked list, add those numbers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment