Thursday, August 13, 2009

polynomial addtion using linked list

#include
#include
#include

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

{
15.
printf("\n enter coeff:");
16.
scanf("%d",&node->coeff);
17.
printf("\n enter power:");
18.
scanf("%d",&node->pow);
19.
node->next=(struct link*)malloc(sizeof(struct link));
20.
node=node->next;
21.
node->next=NULL;
22.
printf("\n continue(y/n):");
23.
ch=getch();
24.
}
25.
while(ch=='y' || ch=='Y');
26.
}
27.
void show(struct link *node)
28.
{
29.
while(node->next!=NULL)
30.
{
31.
printf("%dx^%d",node->coeff,node->pow);
32.
node=node->next;
33.
if(node->next!=NULL)
34.
printf("+");
35.
}
36.
}
37.
void polyadd(struct link *poly1,struct link *poly2,struct link *poly)
38.
{
39.
while(poly1->next && poly2->next)
40.
{
41.
if(poly1->pow>poly2->pow)
42.
{
43.
poly->pow=poly1->pow;
44.
poly->coeff=poly1->coeff;
45.
poly1=poly1->next;
46.
}
47.
else if(poly1->powpow)
48.
{
49.
poly->pow=poly2->pow;
50.
poly->coeff=poly2->coeff;
51.
poly2=poly2->next;
52.
}
53.
else
54.
{
55.
poly->pow=poly1->pow;
56.
poly->coeff=poly1->coeff+poly2->coeff;
57.
poly1=poly1->next;
58.
poly2=poly2->next;
59.
}
60.
poly->next=(struct link *)malloc(sizeof(struct link));
61.
poly=poly->next;
62.
poly->next=NULL;
63.
}
64.
while(poly1->next || poly2->next)
65.
{
66.
if(poly1->next)
67.
{
68.
poly->pow=poly1->pow;
69.
poly->coeff=poly1->coeff;
70.
poly1=poly1->next;
71.
}
72.
if(poly2->next)
73.
{
74.
poly->pow=poly2->pow;
75.
poly->coeff=poly2->coeff;
76.
poly2=poly2->next;
77.
}
78.
poly->next=(struct link *)malloc(sizeof(struct link));
79.
poly=poly->next;
80.
poly->next=NULL;
81.
}
82.
}
83.
main()
84.
{
85.
char ch;
86.
do{
87.
poly1=(struct link *)malloc(sizeof(struct link));
88.
poly2=(struct link *)malloc(sizeof(struct link));
89.
poly=(struct link *)malloc(sizeof(struct link));
90.
printf("\nenter 1st number:");
91.
create(poly1);
92.
printf("\nenter 2nd number:");
93.
create(poly2);
94.
printf("\n1st Number:");
95.
show(poly1);
96.
printf("\n2nd Number:");
97.
show(poly2);
98.
polyadd(poly1,poly2,poly);
99.
printf("\nAdded polynomial:");
100.
show(poly);
101.
printf("\n add two more numbers:");
102.
ch=getch();
103.
}
104.
while(ch=='y' || ch=='Y');
105.
}

No comments:

Post a Comment