-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPolynomial-Multiplication-Using-LinkedList.c
133 lines (132 loc) · 2.71 KB
/
Polynomial-Multiplication-Using-LinkedList.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>
struct node{
int coef,expo;
struct node *next;
};
typedef struct node *Node;
Node getnode();
Node readpoly(Node);
Node insert(Node,int,int);
Node mul(Node,Node);
void display(Node);
Node simplify(Node);//to simplify the polynomial to least no of terms
int main()
{
Node poly1=NULL,poly2=NULL,poly3=NULL;
printf("enter poly 1\n");
poly1=readpoly(poly1);
printf("enter poly2\n");
poly2=readpoly(poly2);
printf("poly 1 is\n");
display(poly1);
printf("poly 2 is\n");
display(poly2);
printf("result\n");
poly3=mul(poly1,poly2);
display(poly3);
printf("simplified\n");
poly3=simplify(poly3);
display(poly3);
return 0;
}
Node getnode()
{
Node newnode;
newnode=(Node)malloc(sizeof(struct node));
return newnode;
}
Node readpoly(Node head)
{
int i,expo,coef,n;
printf("enter no of terms poly\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter cof and expo for %d term\n",i+1);
scanf("%d%d",&coef,&expo);
head=insert(head,coef,expo);
}
return head;
}
Node insert(Node head,int coef,int expo)
{
Node newnode=getnode();
newnode->coef=coef;
newnode->expo=expo;
newnode->next=NULL;
if(head==NULL)
{return newnode;}
else
{
Node temp=head;
while(temp->next!=NULL)
{temp=temp->next;}
temp->next=newnode;
return head;
}
}
Node mul(Node p1,Node p2)
{
Node res=NULL,p,q;
p=p1;
q=p2;
if(p==NULL||q==NULL)
{printf(" one poly does not exist.\n");
exit(0);}
while(p!=NULL)
{
q=p2;
while(q!=NULL)
{
res=insert(res,p->coef*q->coef,p->expo+q->expo);
q=q->next;
}
p=p->next;
}
return res;
}
void display(Node head)
{
Node temp=head;
if(head==NULL)
{printf("no poly exists\n");
return;
}
while(temp!=NULL)
{
if(temp->coef!=0)
{printf("%+d*X^%d ",temp->coef,temp->expo);}
temp=temp->next;
}
// if(temp->coef!=0)
// printf("%d*X^%d",temp->coef,temp->expo);
printf("\n");
}
Node simplify(Node head)
{
Node temp,new=NULL;
temp=head;
new=NULL;
int deg=0,i,nc;
while(temp!=NULL)
{
if(temp->expo>deg)
{deg=temp->expo;}
temp=temp->next;
}
for(i=0;i<=deg;i++)
{
temp=head;
nc=0;
while(temp!=NULL)
{
if(temp->expo==i)
{nc=nc+temp->coef;}
temp=temp->next;
}
if(nc!=0)
{new=insert(new,nc,i);}
}
return new;
}