-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolynomial_ll.c
133 lines (125 loc) · 2.64 KB
/
polynomial_ll.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
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node
{
int coeff;
int expo;
struct node*next;
}*poly1=NULL;struct node*poly2=NULL;
void create1()
{
int num,i=0;
struct node *t,*last=NULL;
printf("Enter the no. of elements in 1st polynomial\n");
scanf("%d",&num);
printf("Enter the coeff elements and their exponents\n");
for(i=0;i<num;i++)
{
t=(struct node*)malloc(sizeof(struct node));
scanf("%d%d",&t->coeff,&t->expo);
t->next=NULL;
if(poly1==NULL)
{
poly1=last=t;
}
else{
last->next=t;
last=t;
}
}
}
void create2()
{
int num,i=0;
struct node *t,*last=NULL;
printf("Enter the no. of elements in 2nd polynomial\n");
scanf("%d",&num);
printf("Enter the coeff elements and their exponents\n");
for(i=0;i<num;i++)
{
t=(struct node*)malloc(sizeof(struct node));
scanf("%d%d",&t->coeff,&t->expo);
t->next=NULL;
if(poly2==NULL)
{
poly2=last=t;
}
else{
last->next=t;
last=t;
}
}
}
void display(struct node *p)
{
while(p)
{
printf("%dx^%d+",p->coeff,p->expo);
p=p->next;
}
printf("\n");
}
void add(struct node **result)
{
struct node*p=poly1,*q=poly2;
struct node *res=NULL,*last=NULL;
res=(struct node*)malloc(sizeof(struct node));
res->next=NULL;
*result=res;
while(p&&q)
{
if(p->expo>q->expo)
{
res->coeff=p->coeff;
res->expo=p->expo;
p=p->next;
}
else if(p->expo<q->expo)
{
res->coeff=q->coeff;
res->expo=q->expo;
q=q->next;
}
else
{
res->coeff=p->coeff+q->coeff;
res->expo=p->expo;
p=p->next;
q=q->next;
}
if(p&&q)
{
res->next=(struct node*)malloc(sizeof(struct node));
res=res->next;
res->next=NULL;
}
}
while(p||q)
{
res->next=(struct node*)malloc(sizeof(struct node));
res=res->next;
res->next=NULL;
if(p)
{ res->coeff=p->coeff;
res->expo=p->expo;
p=p->next;
}
else if(q)
{
res->coeff=q->coeff;
res->expo=q->expo;
q=q->next;
}
}
}
void main()
{
struct node *result;
create1();
create2();
display(poly1);
display(poly2);
add(&result);
display(result);
}