数据结构,一元多项式的乘法与加法运算,C语言代
时间: 2023-06-19 07:02:56 浏览: 140
表如下:
```
typedef struct node {
float coef; // 系数
int expn; // 次数
struct node *next; // 指向下一个节点的指针
} Node, *Polynomial;
```
其中,`Node` 表示一个节点,`Polynomial` 表示一个多项式,即由多个节点组成的链表。链表中每个节点存储一个单项式,由系数 `coef` 和指数 `expn` 组成。链表的头节点不存储任何单项式,其 `coef` 和 `expn` 值可以随意设置。
下面是一元多项式的加法运算代码:
```c
Polynomial add(Polynomial p1, Polynomial p2) {
Polynomial head = (Polynomial) malloc(sizeof(Node)); // 头节点
head->next = NULL;
Polynomial tail = head; // 尾节点
while (p1 && p2) {
if (p1->expn == p2->expn) { // 指数相同
float sum = p1->coef + p2->coef;
if (sum != 0) { // 系数之和不为0
Polynomial temp = (Polynomial) malloc(sizeof(Node));
temp->coef = sum;
temp->expn = p1->expn;
temp->next = NULL;
tail->next = temp;
tail = temp;
}
p1 = p1->next;
p2 = p2->next;
} else if (p1->expn > p2->expn) { // p1 的指数大于 p2 的指数
Polynomial temp = (Polynomial) malloc(sizeof(Node));
temp->coef = p1->coef;
temp->expn = p1->expn;
temp->next = NULL;
tail->next = temp;
tail = temp;
p1 = p1->next;
} else { // p1 的指数小于 p2 的指数
Polynomial temp = (Polynomial) malloc(sizeof(Node));
temp->coef = p2->coef;
temp->expn = p2->expn;
temp->next = NULL;
tail->next = temp;
tail = temp;
p2 = p2->next;
}
}
while (p1) { // 将 p1 中剩余的单项式加入结果多项式中
Polynomial temp = (Polynomial) malloc(sizeof(Node));
temp->coef = p1->coef;
temp->expn = p1->expn;
temp->next = NULL;
tail->next = temp;
tail = temp;
p1 = p1->next;
}
while (p2) { // 将 p2 中剩余的单项式加入结果多项式中
Polynomial temp = (Polynomial) malloc(sizeof(Node));
temp->coef = p2->coef;
temp->expn = p2->expn;
temp->next = NULL;
tail->next = temp;
tail = temp;
p2 = p2->next;
}
return head;
}
```
下面是一元多项式的乘法运算代码:
```c
Polynomial multiply(Polynomial p1, Polynomial p2) {
Polynomial head = (Polynomial) malloc(sizeof(Node)); // 头节点
head->next = NULL;
while (p1) {
Polynomial temp_head = (Polynomial) malloc(sizeof(Node)); // 暂存结果多项式的头节点
temp_head->next = NULL;
Polynomial temp_tail = temp_head; // 暂存结果多项式的尾节点
while (p2) {
Polynomial temp = (Polynomial) malloc(sizeof(Node)); // 创建新节点
temp->coef = p1->coef * p2->coef;
temp->expn = p1->expn + p2->expn;
temp->next = NULL;
temp_tail->next = temp; // 添加到结果多项式中
temp_tail = temp;
p2 = p2->next;
}
head = add(head, temp_head->next); // 将暂存结果多项式与当前结果多项式相加
p1 = p1->next;
}
return head;
}
```
阅读全文