Code:
#include<stdio.h>
#include<malloc.h>
struct node
{
int exp;
int coef;
struct node * link;
};
struct node * create_list(struct node *,int,int);
void display(struct node *);
struct node * add(struct node *,struct node *);
int main()
{
int i,n,co,ex,n2,i2,co2,ex2,n1;
struct node *p1;
struct node *p2;
struct node *r;
r=NULL;
p1=NULL;
p2=NULL;
printf("\nHow many elements needed for first polyn?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the coeffecient and exponent respectively,in descending order of exponent\n");
scanf("%d %d",&co,&ex);
p1= create_list(p1,co,ex); /*creating first linked-list*/
}
printf("\nHow many elements needed for second polyn?");
scanf("%d",&n2);
for(i2=0;i2<n2;i2++)
{
printf("\nEnter the coeffecient and exponent respectively,in descending order of exponent\n");
scanf("%d %d",&co2,&ex2);
p2= create_list(p2,co2,ex2); /*creating 2nd polynomial linked-list*/
}
printf("the first polnomial is::\n");
display(p1); /*displaying*/
printf("the second is::\n");
display(p2);
r=add(p1,p2);
display(r);
return(0);
}
struct node* create_list(struct node *start,int c,int e)
{
struct node *tmp;
struct node *ptr;
tmp=malloc(sizeof(struct node));
tmp->coef=c;
tmp->exp=e;
tmp->link=NULL;
if(start==NULL)
{
start=tmp;
}
else
{
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=tmp;
}
return(start);
}
void display(struct node *s)
{
struct node *ptr=s;
if(s==NULL)
{
printf("You did not enter any elements\n");
}
else
{ printf("\nThe data is::");
while(ptr!=NULL)
{
printf("+\t%d*x^%d\t",ptr->coef,ptr->exp);
ptr=ptr->link;
}
}
}
struct node * add(struct node *a1_strt,struct node *a2_strt)
{
struct node *a3;
a3=malloc(sizeof(struct node));
struct node *a1=a1_strt;
struct node *a2=a2_strt;
while(a1!=NULL && a2!=NULL)
{
if(a1->exp==(a2->exp))
{
a3->exp=a1->exp;
a3->coef=(a1->coef)+(a2->coef);
a3=a3->link;
a1=a1->link;
a2=a2->link;
}
else if((a1->exp)>(a2->exp))
{
a3->exp=a1->exp;
a3->coef=a1->coef;
a3=a3->link;
a1=a1->link;
}
else
{
a3->exp=a2->exp;
a3->coef=a2->coef;
a3=a3->link;
a2=a2->link;
}
}
if(a1==NULL)
{
while(a2!=NULL)
{
a3->exp=a2->exp;
a3->coef=a2->coef;
a3=a3->link;
a2=a2->link;
}
}
else
{
while(a1!=NULL)
{
a3->exp=a1->exp;
a3->coef=a1->coef;
a3=a3->link;
a1=a1->link;
}
}
return(a3);
}