-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
39 lines (33 loc) · 889 Bytes
/
Solution.cpp
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
struct PolyNode {
int coefficient, power;
PolyNode* next;
PolyNode() : coefficient(0), power(0), next(nullptr) {};
PolyNode(int x, int y) : coefficient(x), power(y), next(nullptr) {};
PolyNode(int x, int y, PolyNode* next)
: coefficient(x), power(y), next(next) {};
};
class Solution {
public:
PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) {
if (!poly1) {
return poly2;
}
if (!poly2) {
return poly1;
}
if (poly1->power == poly2->power) {
poly1->coefficient += poly2->coefficient;
poly1->next = addPoly(poly1->next, poly2->next);
if (poly1->coefficient == 0) {
return poly1->next;
}
return poly1;
}
if (poly1->power > poly2->power) {
poly1->next = addPoly(poly1->next, poly2);
return poly1;
}
poly2->next = addPoly(poly1, poly2->next);
return poly2;
}
};