-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathaddtwopolynomialsusinglinkedlist.c
121 lines (109 loc) · 2.22 KB
/
addtwopolynomialsusinglinkedlist.c
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
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int co;
int pow;
struct Node* next;
};
void read_Poly(struct Node** poly)
{
int co, exp, cont;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
*poly = temp;
do{
printf("\n Coeffecient: ");
scanf("%d", &co);
printf("\n Exponent: ");
scanf("%d", &exp);
temp->co = co;
temp->pow = exp;
temp-> next = NULL;
printf(“\nMore terms present? 1 for y and 0 for no: ");
scanf("%d", &cont);
if(cont)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}while(cont);
}
void display_Poly(struct Node* poly)
{
printf("\nPolynomial expression ");
while(poly != NULL)
{
printf("%dX^%d", poly->co, poly->pow);
poly = poly->next;
if(poly != NULL)
printf("+");
}
}
void add_Poly(struct Node** result, struct Node* first, struct Node* second)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL;
*result = temp;
while(first && second)
{
if(first->pow > second->pow)
{
temp->co = first->co;
temp->pow = first->pow;
first = first->next;
}
else if(first->pow < second->pow)
{
temp->co = second->co;
temp->pow = second->pow;
second = second->next;
}
else
{
temp->co = first->co + second->co;
temp->pow = first->pow;
first = first->next;
second = second->next;
}
if(first && second)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}
while(first || second)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
if(first)
{
temp->co = first->co;
temp->pow = first->pow;
first = first->next;
}
else if(second)
{
temp->co = second->co;
temp->pow = second->pow;
second = second->next;
}
}
}
Void main()
{
struct Node* first = NULL;
struct Node* second = NULL;
struct Node* result = NULL;
printf("\nEnter data:-\n");
printf("\nFirst polynomial is:\n");
read_Poly(&first);
display_Poly(first);
printf("\nSecond polynomial is:\n");
read_Poly(&second);
display_Poly(second);
add_Poly(&result, first, second);
display_Poly(result);
}