ad

Thursday, 5 July 2012

program for polynomial addition using linked list

//program for polynomial addition using linked list
#include< stdio.h >
#include< malloc.h >
#include< conio.h >
struct link
{
int coeff;
int pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
void create(struct link *node)
{
char ch;
do
{
printf("\n Enter coefficient:");
scanf("%d",&node->coeff);
printf("\n Enter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
printf("\n continue(y/n):?");
ch=getch();
}
while(ch=='y' || ch=='Y');
}
void show(struct link *node)
{
while(node->next!=NULL)
{
printf("%dx^%d",node->coeff,node->pow);
node=node->next;
if(node->next!=NULL)
printf("+");
}
}
void polyadd(struct link *poly1,struct link *poly2,struct link *poly)
{
while(poly1->next && poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->powpow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}
void main()
{
clrscr();
poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
printf("\n\n\t\t***POLINOMIAL ADDITION***\n\n");
printf("\nEnter 1st polinomial\n");
printf("--------------------\n");
create(poly1);
printf("\n\nEnter 2nd polinomial\n");
printf("--------------------\n");
create(poly2);
printf("\n\n\t\t1st polinomial: ");
show(poly1);
printf("\n\n\t\t2nd polinomial: ");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\n\n\tAdded polynomial: ");
show(poly);
getch();
}


















--------------------------------------------output----------------------------------------------

***POLINOMIAL ADDITION***

Enter 1st polinomial
-------------------------
Enter coefficient:3
Enter power:2
continue(y/n):? y
Enter coefficient:2
Enter power:1
continue(y/n):? y
Enter coefficient:4
Enter power:0
continue(y/n):? n

Enter 2nd polinomial
---------------------------
Enter coefficient:4
Enter power:2
continue(y/n):? y
Enter coefficient:5
Enter power:1
continue(y/n):? y
Enter coefficient:7
Enter power:0
continue(y/n):? n

1st polinomial: 3x^2+2x^1+4x^0

2nd polinomial: 4x^2+5x^1+7x^0

Added polynomial: 7x^2+7x^1+11x^0

No comments:

Post a Comment