-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolyMultiply.c
More file actions
112 lines (78 loc) · 1.5 KB
/
polyMultiply.c
File metadata and controls
112 lines (78 loc) · 1.5 KB
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
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int coeff;
int exp;
struct Node *next;
} Node;
Node *createNode(int coeff, int exp)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->coeff = coeff;
newNode->exp = exp;
newNode->next = NULL;
return newNode;
}
Node *insertEnd(Node *head, int coeff, int exp)
{
Node *temp = createNode(coeff, exp);
if (head == NULL)
return temp;
Node *cur = head;
while (cur->next != NULL)
cur = cur->next;
cur->next = temp;
return head;
}
Node *addPoly(Node *p1, Node *p2)
{
Node *result = NULL, *last = NULL;
Node* temp2 = p2;
while (p1 != NULL){
p2 = temp2;
Node *temp = NULL;
while (p2 != NULL)
{
temp = createNode((p1->coeff * p2->coeff), (p1->exp + p2->exp));
p2 = p2->next;
if (result == NULL)
result = temp;
else
last->next = temp;
last = temp;
}
p1 = p1->next;
}
return result;
}
void printPoly(Node *head)
{
while (head)
{
printf("%dx^%d", head->coeff, head->exp);
if (head->next)
printf(" + ");
head = head->next;
}
printf("\n");
}
int main()
{
Node *p1 = NULL, *p2 = NULL;
\
p1 = insertEnd(p1, 5, 3);
p1 = insertEnd(p1, 4, 1);
p1 = insertEnd(p1, 2, 0);
p2 = insertEnd(p2, 3, 3);
p2 = insertEnd(p2, 1, 2);
p2 = insertEnd(p2, 2, 1);
printf("P1: ");
printPoly(p1);
printf("P2: ");
printPoly(p2);
Node *sum = addPoly(p1, p2);
printf("Sum: ");
printPoly(sum);
return 0;
}