一元多项式的加法运算源代码
时间: 2023-10-16 19:33:37 浏览: 94
以下是一元多项式的加法运算的源代码,其中采用了链表结构存储多项式:
```c++
#include <iostream>
using namespace std;
// 定义多项式节点的结构体
struct PolyNode {
int coef; // 系数
int exp; // 指数
PolyNode* next; // 指向下一个节点的指针
};
// 定义多项式的类型
typedef PolyNode* Polynomial;
// 创建一个空的多项式
void createPoly(Polynomial& poly) {
poly = new PolyNode;
poly->coef = 0;
poly->exp = -1;
poly->next = NULL;
}
// 释放多项式的空间
void destroyPoly(Polynomial& poly) {
PolyNode* p = poly;
while (p != NULL) {
PolyNode* q = p;
p = p->next;
delete q;
}
}
// 插入一个节点到多项式中
void insertNode(Polynomial& poly, int coef, int exp) {
PolyNode* p = poly;
while (p->next != NULL && p->next->exp > exp) {
p = p->next;
}
if (p->next == NULL || p->next->exp < exp) {
PolyNode* q = new PolyNode;
q->coef = coef;
q->exp = exp;
q->next = p->next;
p->next = q;
} else {
p->next->coef += coef;
if (p->next->coef == 0) {
PolyNode* q = p->next;
p->next = q->next;
delete q;
}
}
}
// 从标准输入读入一个多项式
void readPoly(Polynomial& poly) {
int n, coef, exp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> coef >> exp;
insertNode(poly, coef, exp);
}
}
// 输出一个多项式到标准输出
void printPoly(Polynomial poly) {
bool first = true;
PolyNode* p = poly->next;
while (p != NULL) {
if (first) {
first = false;
} else {
cout << " ";
}
cout << p->coef << " " << p->exp;
p = p->next;
}
if (first) {
cout << "0 0";
}
cout << endl;
}
// 多项式的加法运算
void addPoly(Polynomial poly1, Polynomial poly2, Polynomial& result) {
createPoly(result);
PolyNode* p1 = poly1->next;
PolyNode* p2 = poly2->next;
while (p1 != NULL && p2 != NULL) {
if (p1->exp > p2->exp) {
insertNode(result, p1->coef, p1->exp);
p1 = p1->next;
} else if (p1->exp < p2->exp) {
insertNode(result, p2->coef, p2->exp);
p2 = p2->next;
} else {
int coef = p1->coef + p2->coef;
if (coef != 0) {
insertNode(result, coef, p1->exp);
}
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
insertNode(result, p1->coef, p1->exp);
p1 = p1->next;
}
while (p2 != NULL) {
insertNode(result, p2->coef, p2->exp);
p2 = p2->next;
}
}
int main() {
Polynomial poly1, poly2, result;
createPoly(poly1);
createPoly(poly2);
readPoly(poly1);
readPoly(poly2);
addPoly(poly1, poly2, result);
printPoly(result);
destroyPoly(poly1);
destroyPoly(poly2);
destroyPoly(result);
return 0;
}
```
该程序可以从标准输入中读入两个多项式,然后对它们进行加法运算,最后将结果输出到标准输出。多项式的每一项由系数和指数组成,例如 "3x^2" 表示系数为 3,指数为 2 的项。多项式的系数和指数可以是整数或浮点数。
阅读全文