Saturday, February 7, 2015

Adding large numbers using linked list in C++

#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
node *next;
};
void display(node *l)
{
node *s;
s=l;
while(s!=NULL)
{
cout<<s->data;
s=s->next;
}
}
node *add(node *p,node *q)
{
node *t,*l;
int d;
t=NULL;
while(p!=NULL && q!=NULL)
{
d=p->data+q->data;
p=p->next;
q=q->next;
if(d>9)
{
d-=10;
if(p==NULL)
{
p=new(node);
p->data=0;
p->next=NULL;
}
if(q==NULL)
{
q=new(node);
q->data=0;
q->next=NULL;
}
p->data+=1;
}
if(t==NULL)
{
t=new(node);
t->data=d;
t->next=NULL;
}
else
{
l=new(node);
l->data=d;
l->next=t;
t=l;
}
if(p==NULL && q==NULL)
break;
if(p==NULL)
{
p=new(node);
p->data=0;
p->next=NULL;
}
if(q==NULL)
{
q=new(node);
q->data=0;
q->next=NULL;
}
}
return l;
}
int main()
{
node *s1,*s2,*l,*t;
int d;
cout<<"\nEnter the no's....Press -1 for aboting....:\n";
cin>>d;
t=new(node);
t->data=d;
t->next=NULL;
cin>>d;
while(d!=-1)
{
l=new(node);
l->data=d;
l->next=t;
t=l;
cin>>d;
}
s1=l;
cout<<"\nEnter the no's....Press -1 for aboting....:\n";
cin>>d;
t=new(node);
t->data=d;
t->next=NULL;
cin>>d;
while(d!=-1)
{
l=new(node);
l->data=d;
l->next=t;
t=l;
cin>>d;
}
s2=l;
l=add(s1,s2);
cout<<"Thus the addn is:\n";
display(l);
}

No comments:

Post a Comment

Contributors

Translate