forked from sahilbansalweb/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_polynomial_linked_list.c
129 lines (118 loc) · 2.57 KB
/
add_polynomial_linked_list.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
#include<stdlib.h>
#include<stdio.h>
// using namespace std;
struct node{
float coeff;
int expo;
struct node * link;
};
struct node* insert(struct node* head,float co,int ex)
{
struct node* temp;
struct node*newP=malloc(sizeof(struct node));
newP->coeff =co;
newP->expo=ex;
newP->link=NULL;
if(head==NULL || ex>head->expo)
{ newP->link=head;
head=newP;
}
else{
temp=head;
while (temp->link!=NULL && temp->link->expo>=ex)
{
temp=temp->link;
}
newP->link=temp->link;
temp->link=newP;
}
return head;
}
void print(struct node* head)
{
if(head==NULL)
{
printf("empty list");
}
else{
struct node* temp=head;
while (temp!=NULL)
{
printf("(%.1fx^%d)",temp->coeff,(int) temp->expo);
temp=temp->link;
if(temp!=NULL)
{
printf("+");
}
else
{
printf("\n");
}
}
}
}
void polyAdd(struct node* head1,struct node* head2)
{
struct node* ptr1=head1;
struct node* ptr2=head2;
struct node* head3=NULL;
while (ptr1!=NULL && ptr2!=NULL)
{
if(ptr1->expo == ptr2->expo)
{
head3=insert(head3,ptr1->coeff + ptr2->coeff,ptr1->expo);
ptr1=ptr1->link;
ptr2=ptr2->link;
}
else if(ptr1->expo >ptr2->expo)
{
head3=insert(head3,ptr1->coeff,ptr1->expo);
ptr1=ptr1->link;
}
else if (ptr1->expo <ptr2->expo)
{
head3=insert(head3,ptr2->coeff,ptr2->expo);
ptr2=ptr2->link;
}
}
while(ptr1!=NULL)
{
head3=insert(head3,ptr1->coeff,ptr1->expo);
ptr1=ptr1->link;
}
while(ptr2!=NULL)
{
head3=insert(head3,ptr2->coeff,ptr2->expo);
ptr2=ptr2->link;
}
printf("Added polynomial is : ");
print(head3);
}
struct node* create(struct node* head)
{
int n,i;
float coeff;
int expo;
printf("enter the num of terms: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the coeff for %d:",i+1);
scanf("%f",&coeff);
printf("enter the expo for %d:",i+1);
scanf("%d",&expo);
head=insert(head,coeff,expo);
}
return head;
}
int main()
{
struct node* head1=NULL;
struct node* head2=NULL;
printf("enter the first polynomial\n");
head1=create(head1);
printf("enter the second polynomial\n");
head2=create(head2);
polyAdd(head1,head2);
return 0;
}