Header Ads Widget

Program to represent polynomial expression and add them by using link list

 program:-

#include<stdio.h>
#include<stdlib.h>
struct node
{
int coefficient ;
int exponential;
struct node *link;
};
struct node *resultant=NULL;

// function for create Polynomial

struct node *CreatPolynomial()
{
struct node *temp,*x,*t;
t=NULL;
x=t;
while(1)
{
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter coefficient: for end of Polynomial enter coefficient 0\n");
scanf("%d",&temp->coefficient);
if(temp->coefficient==0)
break;
printf("Enter exponent\n");
scanf("%d",&temp->exponential);
temp->link=NULL;
if(t==NULL)
{
t=temp;
x=temp;
}
else
{
while(x->link!=NULL)
x=x->link;
x->link=temp;
}
}
return(t);
}

// function for display Polynomial

void display(struct node *temp)
{
int flag=0;
while(temp!=NULL)
{
if(flag!=0)
printf("+");
printf("%dx^%d",temp->coefficient,temp->exponential);
temp=temp->link;
flag=1;
}
}

// function for creat and insert node in resultant
struct node* insert(int coeff,int expo)
{
struct node * new_node;
new_node=(struct node*)malloc(sizeof(struct node));
new_node->exponential=expo;
new_node->coefficient=coeff;
new_node->link=NULL;
return (new_node);
}

// function for addition

void add(struct node *f,struct node*s)
{
struct node *t,*temp;
while(f!=NULL && s!=NULL)
{
if(f->exponential>s->exponential)
{
t=insert(f->coefficient,f->exponential);
f=f->link;
}
else
{
if(f->exponential<s->exponential)
{
t=insert(s->coefficient,s->exponential);
s=s->link;
}
else
{
if(f->exponential==s->exponential)
{
t=insert(f->coefficient+s->coefficient,f->exponential);
f=f->link;
s=s->link;
}
}
}
if(resultant==NULL)
resultant=t;
else
{
temp=resultant;
while(temp->link!=NULL)
temp=temp->link;
temp->link=t;
}
}
if(f==NULL)
{
while(temp->link!=NULL)
temp=temp->link;
temp->link=s;
}
if(s==NULL)
{
while(temp->link!=NULL)
temp=temp->link;
temp->link=f;
}
}
int main()
{
struct node *first,*second,*result;
int ch;
printf("1. Creat the first Polynomial\n");
printf("2. Creat the second Polynomial\n");
printf("3. display first\n");
printf("4. display second\n");
printf("5. Add both Polynomial\n");
printf("6. display resultant Polynomial\n");
printf("7. exit\n");
while(1)
{
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: first=CreatPolynomial();
continue;
case 2: second=CreatPolynomial();
continue;
case 3: display(first);
break;
case 4: display(second);
break;
case 5: add(first,second);
break;
case 6: display(resultant);
break;
case 7: exit(0);
}
}
return 0;
}