链表多项式相加c++
时间: 2023-10-27 07:08:23 浏览: 170
链表多项式相加的C++代码如下:
```c++
#include <iostream>
using namespace std;
struct Node {
int coef; // 系数
int exp; // 指数
Node* next;
Node(int c, int e) : coef(c), exp(e), next(nullptr) {}
};
Node* addPolynomial(Node* p1, Node* p2) {
Node* dummy = new Node(0, 0);
Node* cur = dummy;
while (p1 && p2) {
if (p1->exp > p2->exp) {
cur->next = new Node(p1->coef, p1->exp);
p1 = p1->next;
} else if (p1->exp < p2->exp) {
cur->next = new Node(p2->coef, p2->exp);
p2 = p2->next;
} else {
int sum = p1->coef + p2->coef;
if (sum != 0) {
cur->next = new Node(sum, p1->exp);
}
p1 = p1->next;
p2 = p2->next;
}
cur = cur->next;
}
cur->next = p1 ? p1 : p2;
return dummy->next;
}
int main() {
Node* p1 = new Node(3, 4);
p1->next = new Node(2, 3);
p1->next->next = new Node(5, 1);
cout << "p1: ";
for (Node* cur = p1; cur != nullptr; cur = cur->next) {
cout << cur->coef << "x^" << cur->exp << " + ";
}
cout << "0" << endl;
Node* p2 = new Node(4, 3);
p2->next = new Node(1, 2);
p2->next->next = new Node(2, 1);
p2->next->next->next = new Node(6, 0);
cout << "p2: ";
for (Node* cur = p2; cur != nullptr; cur = cur->next) {
cout << cur->coef << "x^" << cur->exp << " + ";
}
cout << "0" << endl;
Node* sum = addPolynomial(p1, p2);
cout << "sum: ";
for (Node* cur = sum; cur != nullptr; cur = cur->next) {
cout << cur->coef << "x^" << cur->exp << " + ";
}
cout << "0" << endl;
return 0;
}
```
阅读全文