用两个线性链表分别存储两个一元多项式,试实现两个多项式的加法/减法运算。 [基本要求] 一元多项式用链式存储结构实现存储; 注意: 1、多项式表的链表定义方法 2、注意临界状态的处理。的源代码
时间: 2023-06-12 21:03:42 浏览: 99
最新数据结构-利用线性表链式存储实现一元多项式相加减-课程设计-实验报告.doc
以下C++实现:
```cpp
#include <iostream>
using namespace std;
// 定义多项式的项
typedef struct PolyNode {
float coef; // 系数
int expn; // 指数
struct PolyNode *next; // 指向下一项的指针
} PolyNode, *Polynomial;
// 创建多项式
void createPoly(Polynomial &p) {
p = (PolyNode *) malloc(sizeof(PolyNode)); // 创建头结点
p->next = NULL;
PolyNode *r = p; // r指向尾结点
int n, e;
float c;
cout << "请输入多项式项数:";
cin >> n;
for (int i = 0; i < n; i++) {
cout << "请输入第" << i + 1 << "项的系数和指数:";
cin >> c >> e;
if (c == 0) continue; // 忽略系数为0的项
PolyNode *s = (PolyNode *) malloc(sizeof(PolyNode)); // 创建新结点
s->coef = c;
s->expn = e;
r->next = s;
r = s;
}
r->next = NULL;
}
// 多项式加法
void polyAdd(Polynomial pa, Polynomial pb, Polynomial &pc) {
PolyNode *p1 = pa->next, *p2 = pb->next;
PolyNode *pre = pc = pa; // pa作为结果多项式的头结点
while (p1 && p2) {
if (p1->expn == p2->expn) {
float sum = p1->coef + p2->coef;
if (sum != 0) {
p1->coef = sum;
pre->next = p1;
pre = p1;
} else {
free(p1);
}
p1 = p1->next;
PolyNode *tmp = p2;
p2 = p2->next;
free(tmp);
} else if (p1->expn < p2->expn) {
pre->next = p1;
pre = p1;
p1 = p1->next;
} else {
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
pre->next = p1 ? p1 : p2;
free(pb); // 释放pb的头结点
}
// 多项式减法
void polySub(Polynomial pa, Polynomial pb, Polynomial &pc) {
PolyNode *p1 = pa->next, *p2 = pb->next;
PolyNode *pre = pc = pa; // pa作为结果多项式的头结点
while (p1 && p2) {
if (p1->expn == p2->expn) {
float diff = p1->coef - p2->coef;
if (diff != 0) {
p1->coef = diff;
pre->next = p1;
pre = p1;
} else {
free(p1);
}
p1 = p1->next;
PolyNode *tmp = p2;
p2 = p2->next;
free(tmp);
} else if (p1->expn < p2->expn) {
pre->next = p1;
pre = p1;
p1 = p1->next;
} else {
PolyNode *s = (PolyNode *) malloc(sizeof(PolyNode)); // 创建新结点
s->coef = -p2->coef;
s->expn = p2->expn;
pre->next = s;
pre = s;
p2 = p2->next;
}
}
while (p2) { // 如果p2还有剩余项,全部加入结果多项式
PolyNode *s = (PolyNode *) malloc(sizeof(PolyNode)); // 创建新结点
s->coef = -p2->coef;
s->expn = p2->expn;
pre->next = s;
pre = s;
p2 = p2->next;
}
pre->next = p1; // 如果p1还有剩余项,全部加入结果多项式
free(pb); // 释放pb的头结点
}
// 输出多项式
void printPoly(Polynomial p) {
PolyNode *s = p->next;
if (s == NULL) {
cout << "0" << endl;
return;
}
while (s) {
if (s->coef > 0 && s != p->next) cout << "+";
if (s->coef != 1 || s->expn == 0) cout << s->coef;
if (s->expn > 0) cout << "x";
if (s->expn > 1) cout << "^" << s->expn;
s = s->next;
}
cout << endl;
}
int main() {
Polynomial pa, pb, pc;
createPoly(pa);
createPoly(pb);
cout << "多项式pa:";
printPoly(pa);
cout << "多项式pb:";
printPoly(pb);
polyAdd(pa, pb, pc);
cout << "多项式pa + pb:";
printPoly(pc);
polySub(pa, pb, pc);
cout << "多项式pa - pb:";
printPoly(pc);
return 0;
}
```
注:以上代码中的多项式加法和减法都是将结果存储在第一个多项式中,因此第二个多项式会被释放掉。如果需要保留第二个多项式,可以在函数内部创建一个新的多项式并将结果存储在其中。
阅读全文