-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpolynomial_add_ll.c
126 lines (115 loc) · 3.25 KB
/
polynomial_add_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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node
{
int coefficent;
int degree;
struct node *next;
};
struct node* poly1 = NULL;
struct node* poly2 = NULL;
struct node* poly3 = NULL;
struct node* read_Poly(struct node *poly, int coeff, int deg)
{
struct node *temp = poly;
struct node* newnode = malloc(sizeof(struct node));
newnode->next = NULL;
newnode->coefficent = coeff;
newnode->degree = deg;
if (poly == NULL)
{
poly = newnode;
}
else
{
while (temp->next!= NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
return poly;
}
void display(struct node *poly)
{
while(poly->next!= NULL)
{
printf("%dx^%d+ ",poly->coefficent, poly->degree);
poly = poly->next;
}
printf("%dx^%d\n",poly->coefficent, poly->degree);
}
void addPoly()
{
struct node *newnode = malloc(sizeof(struct node));
newnode->next = NULL;
struct node *temp1 = poly1;
struct node *temp2 = poly2;
struct node *temp3 = poly3;
while (temp1!= NULL && temp2 != NULL)
{
if (temp1->degree == temp2->degree)
{
poly3 = read_Poly(poly3, (temp1->coefficent+temp2->coefficent), temp1->degree);
temp1 = temp1->next;
temp2 = temp2->next;
}
else if (temp1->degree > temp2->degree)
{
poly3 = read_Poly(poly3, temp1->coefficent, temp1->degree);
temp1 = temp1->next;
}
else
{
poly3 = read_Poly(poly3, temp2->coefficent, temp2->degree);
temp2 = temp2->next;
}
}
while (temp1!=NULL)
{
poly3 = read_Poly(poly3, temp1->coefficent, temp1->degree);
temp1 = temp1->next;
}
while (temp2!=NULL)
{
poly3 = read_Poly(poly3, temp2->coefficent, temp2->degree);
temp2 = temp2->next;
}
display(poly3);
}
void main()
{
int choice, coeff, deg;
printf("\nSelect an option:\n");
printf("1. Enter term for polynomial 1\n");
printf("2. Enter term for polynomial 2\n");
printf("3. Perform Addition\n");
printf("4. Exit\n");
while(1)
{
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter coefficient and degree for the term: ");
scanf("%d%d", &coeff, °);
poly1 = read_Poly(poly1, coeff, deg);
break;
case 2:
printf("Enter coefficient and degree for the term: ");
scanf("%d%d", &coeff, °);
poly2 = read_Poly(poly2, coeff, deg);
break;
case 4:
exit(0);
break;
case 3:
addPoly();
break;
default:
printf("Invalid choice!\n");
}
}
}