Polynomial Addition using Linked List
Learn Theory-Polynomials
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coeff,exp;
struct node *link;
}*P1=NULL,*P2=NULL,*P3=NULL,*temp,*lastP3;
struct node * createpoly()
{
struct node *TP=NULL,*temp=NULL,*LTP=NULL;
int n,coeff,exp,i;
printf("\n Enter no of Terms of Poly : ");
scanf("%d",&n);
printf("\n Enter Coefficint and Exponent of Poly in order(k1x^n+k2x^n-1..+knx^0 : ");
for(i=0;i<n;i++)
{
scanf("%d%d",&coeff,&exp);
temp=(struct node*)malloc(sizeof(struct node));
temp->coeff=coeff;
temp->exp=exp;
temp->link=NULL;
if(TP==NULL)
{
TP=temp;
LTP=temp;
}
else
{
LTP->link=temp;
LTP=temp;
}
}
return TP;
}
void displaypoly(struct node*temp)
{
while(temp!=NULL)
{
printf("%dx^%d ---> ",temp->coeff,temp->exp);
temp=temp->link;
}
printf("NULL\n");
}
void createtempnode(int co,int ex)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->coeff=co;
temp->exp=ex;
temp->link=NULL;
}
void addtoP3()
{
if(P3==NULL)
{
P3=temp;
lastP3=temp;
}
else
{
lastP3->link=temp;
lastP3=temp;
}
}
struct node polyadd(struct node*P1, struct node *P2)
{
if(P1==NULL) P3=P2;
else if(P2==NULL) P3=P1;
else
{
while(P1!=NULL && P2!= NULL)
{
if(P1->exp > P2->exp)
{
createtempnode(P1->coeff,P1->exp);
addtoP3();
P1=P1->link;
}
else if(P2->exp > P1->exp)
{
createtempnode(P2->coeff,P2->exp);
addtoP3();
P2=P2->link;
}
else
{
createtempnode(P1->coeff+P2->coeff,P1->exp);
addtoP3();
P1=P1->link;
P2=P2->link;
}
}
while(P1!=NULL)
{
lastP3->link=P1;
lastP3=P1;
P1=P1->link;
}
while(P2!=NULL)
{
lastP3->link=P2;
lastP3=P2;
P2=P2->link;
}
}
}
void main()
{
printf("Create polynomial P1\n");
P1=createpoly();
printf("Create polynomial P2\n");
P2=createpoly();
printf("Polynomial P1\n");
displaypoly(P1);
printf("Polynomial P2\n");
displaypoly(P2);
polyadd(P1,P2);
printf("Sum of polynomial P1 and P2\n");
displaypoly(P3);
}
Comments
Post a Comment