forked from INFOTECHSquad/OpenSource-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PolynomialAdditionWithLinkedList.c
143 lines (135 loc) · 4.11 KB
/
PolynomialAdditionWithLinkedList.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include<stdio.h>
#include<stdlib.h>
struct node
{
int coff;
int pow;
struct node* link;
};
void createpol(struct node** hpol)
{
int n,c,p;
struct node*temp=NULL;
struct node*ptr=NULL;
n=1;
while(n!=0)
{
printf("Enter coefficient and power:\n");
scanf("%d %d",&c,&p);
temp=(struct node*)malloc(sizeof(struct node));
temp->coff=c;
temp->pow=p;
temp->link=NULL;
if(*hpol==NULL)
{
*hpol=temp;
ptr=temp;
}
else
{
ptr->link=temp;
ptr=temp;
}
printf("Enter 1 to continue or 0 to exit\n");
scanf("%d",&n);
}
}
void addpol(struct node**pol1, struct node**pol2, struct node**r)
{
struct node*p1=*pol1;
struct node*p2=*pol2;
struct node* temp=NULL;
struct node* ptr=NULL;
while(p1!=NULL && p2!=NULL)
{
if(p1->pow > p2->pow)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->pow=p1->pow;
temp->coff=p1->coff;
temp->link=NULL;
if(*r==NULL)
{
*r=temp;
ptr=temp;
}
else
{
ptr->link=temp;
ptr=temp;
}
p1=p1->link;
}
else if(p2->pow > p1->pow)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->pow=p2->pow;
temp->coff=p2->coff;
temp->link=NULL;
if(*r==NULL)
{
*r=temp;
ptr=temp;
}
else
{
ptr->link=temp;
ptr=temp;
}
p2=p2->link;
}
else if(p1->pow == p2->pow)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->pow=p1->pow;
temp->coff=p1->coff+p2->coff;
temp->link=NULL;
if(temp->coff!=0)
{
if(*r==NULL)
{
*r=temp;
ptr=temp;
}
else
{
ptr->link=temp;
ptr=temp;
}
}
p2=p2->link;
p1=p1->link;
}
}
}
void display(struct node **hpol)
{
struct node* ptr;
ptr=*hpol;
while(ptr!=NULL)
{
printf("%d x^ %d",ptr->coff,ptr->pow);
ptr=ptr->link;
if(ptr!=NULL)
printf("+");
}
printf("\n");
}
int main()
{
struct node*h1=NULL;
struct node*h2=NULL;
struct node*rh=NULL;
createpol(&h1);
printf("The first polynomial is created\n");
createpol(&h2);
printf("The second polynomial is created\n");
printf("the first polynomial is:\n");
display(&h1);
printf("the second polynomial is:\n");
display(&h2);
addpol(&h1,&h2,&rh);
printf("the result polynomial is:\n");
display(&rh);
return 0;
}