编程实现一个一元多项式加法,用数据结构c语言版
时间: 2023-05-13 10:04:36 浏览: 223
数据结构课程设计报告—一元多项式加法、减法、乘法运算的实现.doc
5星 · 资源好评率100%
可以使用链表来实现一元多项式加法,以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式节点结构体
typedef struct PolyNode {
int coef; // 系数
int expon; // 指数
struct PolyNode *next; // 指向下一个节点的指针
} PolyNode, *Polynomial;
// 创建一个新的多项式节点
PolyNode *createNode(int coef, int expon) {
PolyNode *node = (PolyNode *)malloc(sizeof(PolyNode));
node->coef = coef;
node->expon = expon;
node->next = NULL;
return node;
}
// 将多项式插入到链表中
void insert(Polynomial *p, int coef, int expon) {
PolyNode *node = createNode(coef, expon);
if (*p == NULL) {
*p = node;
} else {
PolyNode *cur = *p;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
}
// 一元多项式加法
Polynomial add(Polynomial p1, Polynomial p2) {
Polynomial result = NULL;
PolyNode *cur1 = p1, *cur2 = p2;
while (cur1 != NULL && cur2 != NULL) {
if (cur1->expon > cur2->expon) {
insert(&result, cur1->coef, cur1->expon);
cur1 = cur1->next;
} else if (cur1->expon < cur2->expon) {
insert(&result, cur2->coef, cur2->expon);
cur2 = cur2->next;
} else {
int sum = cur1->coef + cur2->coef;
if (sum != 0) {
insert(&result, sum, cur1->expon);
}
cur1 = cur1->next;
cur2 = cur2->next;
}
}
while (cur1 != NULL) {
insert(&result, cur1->coef, cur1->expon);
cur1 = cur1->next;
}
while (cur2 != NULL) {
insert(&result, cur2->coef, cur2->expon);
cur2 = cur2->next;
}
return result;
}
// 打印多项式
void print(Polynomial p) {
if (p == NULL) {
printf("0\n");
return;
}
PolyNode *cur = p;
while (cur != NULL) {
printf("%dX^%d", cur->coef, cur->expon);
if (cur->next != NULL) {
printf(" + ");
}
cur = cur->next;
}
printf("\n");
}
int main() {
Polynomial p1 = NULL, p2 = NULL;
insert(&p1, 3, 5);
insert(&p1, 2, 3);
insert(&p1, 1, 1);
print(p1);
insert(&p2, 2, 4);
insert(&p2, 4, 3);
insert(&p2, 2, 1);
print(p2);
Polynomial result = add(p1, p2);
print(result);
return 0;
}
```
以上代码实现了一元多项式加法,使用了链表数据结构来存储多项式。
阅读全文