Saturday, April 12, 2014

Polynomial addition using linked list

Program to implement addition of two polynomials using linked list



PROGRAM

#include<iostream>
#include<cconio>
using namespace std;
struct poly
{
int coeff;
int exp;
poly *next;
};

class polylist
{
poly *start,*last;
public:
void read();
void display();
void sort();
polylist()
{
start=last=NULL;
}
void insertnode(poly*);
polylist operator+(polylist);
};

void polylist::read()
{
int i=0,c,e;
poly *head;
while(1)
{
i++;
cout<<"\nEnter the coefficient & exponent of the term :"<<i<<":";
cin>>c>>e;
if(c==-1)
break;
else
{
head=new poly;
head->coeff=c;
head->exp=e;
head->next=NULL;
if(start==NULL)
start=last=head;
else
{
last->next=head;
last=head;
}
}
}
}
void polylist::display()
{
poly *temp=start;
do
{
cout<<temp->coeff<<" x^ "<<temp->exp;
if(temp->next!=NULL)
cout<<" + ";
temp=temp->next;
}
while(temp!=NULL);
}

polylist polylist::operator+(polylist p2)
{
polylist p3;
poly *t1,*t2,*t3;
t1=start;
t2=p2.start;
while((t1!=NULL)&&(t2!=NULL))
{
t3=new poly;
if(t1->exp > t2->exp)
{
t3->coeff=t1->coeff;
t3->exp=t1->exp;
t3->next=NULL;
t1=t1->next;
}
else if(t1->exp < t2->exp)
{
t3->coeff=t2->coeff;
t3->exp=t2->exp;
t3->next=NULL;
t2=t2->next;
}
else
{
t3->coeff=t1->coeff+t2->coeff;
t3->exp=t1->exp;
t3->next=NULL;
t1=t1->next;
t2=t2->next;
}
p3.insertnode(t3);
}
while(t1!=NULL)
{
t3=new poly;
t3->coeff=t1->coeff;
t3->exp=t1->exp;
t3->next=NULL;
t1=t1->next;
p3.insertnode(t3);
}
while(t2!=NULL)
{
t3=new poly;
t3->coeff=t2->coeff;
t3->exp=t2->exp;
t3->next=NULL;
t2=t2->next;
p3.insertnode(t3);
}
return p3;
}
void polylist::sort()
{
poly *t1,*t2;
int c,e;
for(t1=start;t1->next!=NULL;t1=t1->next)
{
for(t2=t1->next;t2->next!=NULL;t2=t2->next)
{
if(t1->exp < t2->exp)
{
c=t1->coeff;
e=t1->exp;
t1->coeff=t2->coeff;
t1->exp=t2->exp;
t2->coeff=c;
t2->exp=e;
}
}
}
}
void polylist::insertnode(poly *t3)
{
if(start==NULL)
start=last=t3;
else
{
last->next=t3;
last=t3;
}
}

int main()
{
clrscr();
polylist p1,p2,p3;
p1.read();
p1.sort();
cout<<"\n1 st polynomial is :";
p1.display();
p2.read();
p2.sort();
cout<<"\n2 nd polynomial is :";
p2.display();
p3=p1 + p2;
cout<<"\nThe resultant polynomial is :";
p3.display();
getch();
return 0;
}

OUTPUT

Enter the coefficient & exponent of the term :4
5
Enter the coefficient & exponent of the term :3
2
Enter the coefficient & exponent of the term :9
0
Enter the coefficient & exponent of the term :-1
0

1st polynomial is : 4 x^ 5 + 3 x^ 2 + 9 x^ 0

Enter the coefficient & exponent of the term :5
6
Enter the coefficient & exponent of the term :6
5
Enter the coefficient & exponent of the term :7
3
Enter the coefficient & exponent of the term :9
2

2 nd polynomial is : 5 x^ 6 + 6 x^ 5 + 7 x^ 3 + 9 x^ 2

The resultant polynomial is :5 x^ 6 + 10 x^ 5 + 7 x^ 3 + 12 x^ 2 + 9 x^ 0

1 comments: