用c加加设计一个基于链表的两个一元多项式的基本运算
时间: 2023-06-11 22:10:29 浏览: 126
以下是一个基于链表的一元多项式的结构体定义:
```c++
struct PolyNode {
int coef; // 系数
int exp; // 指数
struct PolyNode *next; // 下一个节点
};
typedef struct PolyNode *Polynomial; // 定义多项式类型为指向 PolyNode 的指针
```
以下是两个一元多项式相加的代码实现:
```c++
Polynomial addPoly(Polynomial p1, Polynomial p2) {
Polynomial front, rear, temp;
front = new PolyNode;
rear = front;
while (p1 && p2) {
if (p1->exp > p2->exp) {
rear->next = p1;
p1 = p1->next;
} else if (p1->exp < p2->exp) {
rear->next = p2;
p2 = p2->next;
} else {
int sum = p1->coef + p2->coef;
if (sum) {
temp = new PolyNode;
temp->coef = sum;
temp->exp = p1->exp;
rear->next = temp;
rear = temp;
}
p1 = p1->next;
p2 = p2->next;
}
}
for (; p1; p1 = p1->next) {
temp = new PolyNode;
temp->coef = p1->coef;
temp->exp = p1->exp;
rear->next = temp;
rear = temp;
}
for (; p2; p2 = p2->next) {
temp = new PolyNode;
temp->coef = p2->coef;
temp->exp = p2->exp;
rear->next = temp;
rear = temp;
}
rear->next = nullptr;
return front->next;
}
```
以下是两个一元多项式相乘的代码实现:
```c++
Polynomial mulPoly(Polynomial p1, Polynomial p2) {
if (!p1 || !p2) {
return nullptr;
}
Polynomial p, t1, t2, rear, temp;
t1 = p1;
t2 = p2;
rear = new PolyNode;
p = rear;
while (t2) {
temp = new PolyNode;
temp->coef = t1->coef * t2->coef;
temp->exp = t1->exp + t2->exp;
rear->next = temp;
rear = temp;
t2 = t2->next;
}
t1 = t1->next;
while (t1) {
t2 = p2;
rear = p;
while (t2) {
int c = t1->coef * t2->coef;
int e = t1->exp + t2->exp;
while (rear->next && rear->next->exp > e) {
rear = rear->next;
}
if (rear->next && rear->next->exp == e) {
if (rear->next->coef + c) {
rear->next->coef += c;
} else {
temp = rear->next;
rear->next = temp->next;
delete temp;
}
} else {
temp = new PolyNode;
temp->coef = c;
temp->exp = e;
temp->next = rear->next;
rear->next = temp;
}
t2 = t2->next;
}
t1 = t1->next;
}
temp = p;
p = p->next;
delete temp;
return p;
}
```
以上实现了链表表示的两个一元多项式的基本运算,包括相加和相乘。
阅读全文