forked from pratyushmohapatra33/Poly_AddUsingLinkedLIST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddpoly.c
More file actions
180 lines (150 loc) · 3.04 KB
/
addpoly.c
File metadata and controls
180 lines (150 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include<stdio.h>
#include<malloc.h>
struct poly
{
int cof;
int exp;
struct poly *link;
};
struct poly * create_poly();
struct poly * add_poly();
void traverse(struct poly *);
main()
{
struct poly *base1,*base2,*base3;
base1=create_poly();
traverse(base1);
base2=create_poly();
traverse(base2);
base3=add_poly(base1,base2);
traverse(base3);
}
struct poly * add_poly(struct poly *p,struct poly *q)
{
struct poly *a=0,*b,*temp;
while(p!=0 && q!=0)
{
if(p->exp==q->exp)
{
if(a==0)
{
a=malloc(sizeof(struct poly));
a->cof=p->cof+q->cof;
a->exp=p->exp;
a->link=0;
temp=a;
}
else
{
b=malloc(sizeof(struct poly));
a->link=b;
a=b;
a->cof=p->cof+q->cof;
a->exp=p->exp;
}
a->link=0;
p=p->link;
q=q->link;
}
else
if(p->exp>q->exp)
{
if(a==0)
{
a=malloc(sizeof(struct poly));
a->cof=p->cof;
a->exp=p->exp;
a->link=0;
temp=a;
}
else
{
b=malloc(sizeof(struct poly));
a->link=b;
a=b;
a->cof=p->cof;
a->exp=p->exp;
a->link=0;
}
p=p->link;
}
else
if(p->exp<q->exp)
{
if(a==0)
{
a=malloc(sizeof(struct poly));
a->cof=q->cof;
a->exp=q->exp;
a->link=0;
temp=a;
}
else
{
b=malloc(sizeof(struct poly));
a->link=b;
a=b;
a->cof=q->cof;
a->exp=q->exp;
a->link=0;
}
q=q->link;
}
}//while
//rest node loop
while(p!=0)
{
b=malloc(sizeof(struct poly));
a->link=b;
a=b;
a->cof=p->cof;
a->exp=p->exp;
a->link=0;
p=p->link;
}
//rest node from q
while(q!=0)
{
b=malloc(sizeof(struct poly));
a->link=b;
a=b;
a->cof=q->cof;
a->exp=q->exp;
a->link=0;
q=q->link;
}
a->link=0;
return temp;
}
void traverse(struct poly *p)
{
while(p->link!=0)
{
printf("%dX%d + ",p->cof,p->exp);
p=p->link;
}
printf("%dX%d\n",p->cof,p->exp);
}
struct poly * create_poly()
{
struct poly *p,*q,*temp;
char x[5];
p=malloc(sizeof(struct poly));
printf("Enter coefficient and exponent");
scanf("%d%d",&p->cof,&p->exp);
temp=p;
while(1)
{
printf("Do you want to continue yes/no");
scanf("%s",x);
if(strcmp(x,"no")==0)
break;
q=malloc(sizeof(struct poly));
p->link=q;
p=q;
printf("Enter coefficient and exponent:");
scanf("%d%d",&p->cof,&p->exp);
}
p->link=0;
return temp;
}