-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolynomial_representation_and_addition_using_linked_list.c
115 lines (115 loc) · 2.48 KB
/
polynomial_representation_and_addition_using_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
#include<stdio.h>
#include<stdlib.h>
typedef struct polynomial
{
int pow;
int coeff;
struct polynomial *next;
}poly;
void display(poly*head)
{
poly*p=head;
printf("The polynomials after adding are : \n");
while(p!=NULL)
{
printf("%dx^%d\t",p->coeff,p->pow);
if(p->pow!=0)
printf("+\t");
p=p->next;
}
printf("\n");
}
poly* create(poly*head)
{
poly*temp=(poly*)malloc(sizeof(poly));
if(temp==NULL)
{
printf("OVERFLOW!!!!\n");
return NULL;
}
head=temp;
do
{
printf("Enter the power of variable : ");
scanf("%d",&temp->pow);
printf("Enter the coefficient : ");
scanf("%d",&temp->coeff);
poly *p=temp;
if(p->pow!=0)
{
temp=(poly*)malloc(sizeof(poly));
if(temp==NULL)
{
printf("OVERFLOW!!!!\n");
return NULL;
}
p->next=temp;
}
}while(temp->pow!=0);
temp->next=NULL;
return head;
}
void add(poly*h1,poly*h2)
{
poly*head=(poly*)malloc(sizeof(poly));
poly*temp=head;
while(h1 && h2)
{
if(h1->pow>h2->pow)
{
temp->pow=h1->pow;
temp->coeff=h1->coeff;
h1=h1->next;
}
else if(h2->pow>h1->pow)
{
temp->pow=h2->pow;
temp->coeff=h2->coeff;
h2=h2->next;
}
else
{
temp->pow=h1->pow;
temp->coeff=h1->coeff+h2->coeff;
h1=h1->next;
h2=h2->next;
}
if(h1 || h2)
{
temp->next=(poly*)malloc(sizeof(poly));
temp=temp->next;
}
}
while(h1 || h2)
{
if(h1)
{
temp->pow=h1->pow;
temp->coeff=h1->coeff;
h1=h1->next;
}
if(h2)
{
temp->pow=h2->pow;
temp->coeff=h2->coeff;
h2=h2->next;
}
if(h1 || h2)
{
temp->next=(poly*)malloc(sizeof(poly));
temp=temp->next;
}
}
temp->next=NULL;
display(head);
}
int main()
{
poly*h1=NULL,*h2=NULL,*p1,*p2;
printf("Enter the first polynomial : \n");
h1=create(h1);
printf("Enter the second polynomial : \n");
h2=create(h2);
add(h1,h2);
return 0;
}