forked from AugustineAykara/Data-Structure-In-C
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomialAddition.c
More file actions
141 lines (114 loc) · 1.98 KB
/
polynomialAddition.c
File metadata and controls
141 lines (114 loc) · 1.98 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
#include<stdio.h>
#include<stdlib.h>
struct node{
int coeff;
int exp;
struct node *addr;
}*head = NULL, *h1 = NULL, *h2 = NULL, *h=NULL;
void traversal(struct node *h)
{
struct node *ptr;
ptr = h;
printf("\n");
while(ptr != NULL)
{
printf(" %d^%d +", ptr -> coeff, ptr -> exp);
ptr = ptr -> addr;
}
printf("\n\n");
}
struct node * createNode(int c, int e)
{
struct node *nd;
nd = (struct node *) malloc (sizeof(struct node));
nd -> coeff = c;
nd -> exp = e;
nd -> addr = NULL;
return nd;
}
struct node *createPoly(int s)
{
int i,c,e;
struct node *nd, *ptr;
h=NULL;
for (i = 0; i < s; ++i)
{
printf("\n Entre coefficient : ");
scanf("%d", &c);
printf(" Enter exponent : ");
scanf("%d", &e);
nd = createNode(c,e);
if (h == NULL)
{
h = nd;
ptr = nd;
}
else
{
ptr -> addr = nd;
ptr = nd;
}
}
traversal(h);
return h;
}
void polynomialAddition(struct node *p1, struct node *p2)
{
struct node *add, *ptr;
add = (struct node *) malloc (sizeof(struct node));
while(p1 != NULL && p2 != NULL)
{
if (p1 -> exp > p2 -> exp)
{
add = createNode(p1 -> coeff, p1 -> exp);
p1 = p1 -> addr;
}
else if (p2 -> exp > p1 -> exp)
{
add = createNode(p2 -> coeff, p2 -> exp);
p2 = p2 -> addr;
}
else
{
add = createNode(p1 -> coeff + p2 -> coeff, p1 -> exp);
p1 = p1 -> addr;
p2 = p2 -> addr;
}
if (head == NULL)
{
head = add;
ptr = add;
}
else
{
ptr -> addr = add;
ptr = add;
}
}
while (p1 != NULL)
{
add = createNode(p1 -> coeff, p1 -> exp);
p1 = p1 -> addr;
ptr -> addr = add;
ptr = add;
}
while (p2 != NULL)
{
add = createNode(p2 -> coeff, p2 -> exp);
p2 = p2 -> addr;
ptr -> addr = add;
ptr = add;
}
traversal(head);
}
void main()
{
int s1,s2;
printf("\n Enter the size of first polynomial : ");
scanf("%d", &s1);
h1 = createPoly(s1);
printf("\n Enter the size of second polynomial : ");
scanf("%d", &s2);
h2 = createPoly(s2);
polynomialAddition(h1 ,h2);
}