用C语言实现多项式合并
时间: 2024-02-17 09:02:00 浏览: 37
以下是用C语言实现多项式合并的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct _Term {
int coef; // 系数
int exp; // 指数
struct _Term *next; // 指向下一项的指针
} Term;
// 创建一个新的多项式项
Term *newTerm(int coef, int exp) {
Term *t = (Term *)malloc(sizeof(Term));
if (t == NULL) {
fprintf(stderr, "Error: Unable to allocate memory!\n");
exit(EXIT_FAILURE);
}
t->coef = coef;
t->exp = exp;
t->next = NULL;
return t;
}
// 合并两个多项式
Term *merge(Term *p1, Term *p2) {
Term *head = newTerm(0, 0); // 创建一个空的头节点
Term *tail = head; // 尾指针初始指向头节点
while (p1 != NULL && p2 != NULL) {
if (p1->exp > p2->exp) {
tail->next = newTerm(p1->coef, p1->exp);
p1 = p1->next;
} else if (p1->exp < p2->exp) {
tail->next = newTerm(p2->coef, p2->exp);
p2 = p2->next;
} else {
int coef = p1->coef + p2->coef;
if (coef != 0) {
tail->next = newTerm(coef, p1->exp);
}
p1 = p1->next;
p2 = p2->next;
}
tail = tail->next;
}
// 将剩余的项添加到结果中
if (p1 != NULL) {
tail->next = p1;
}
if (p2 != NULL) {
tail->next = p2;
}
Term *result = head->next;
free(head);
return result;
}
// 输出多项式
void printPoly(Term *poly) {
if (poly == NULL) {
printf("0\n");
return;
}
while (poly != NULL) {
if (poly->coef > 0 && poly != poly->next) {
printf("+");
}
if (poly->coef != 1 || poly->exp == 0) {
printf("%d", poly->coef);
}
if (poly->exp > 1) {
printf("x^%d", poly->exp);
} else if (poly->exp == 1) {
printf("x");
}
poly = poly->next;
}
printf("\n");
}
int main() {
// 创建多项式1:2x^3 + 3x^2 + 4x + 1
Term *p1 = newTerm(2, 3);
p1->next = newTerm(3, 2);
p1->next->next = newTerm(4, 1);
p1->next->next->next = newTerm(1, 0);
printf("p1 = ");
printPoly(p1);
// 创建多项式2:3x^4 + 2x^2 + 5
Term *p2 = newTerm(3, 4);
p2->next = newTerm(2, 2);
p2->next->next = newTerm(5, 0);
printf("p2 = ");
printPoly(p2);
// 合并多项式1和多项式2
Term *result = merge(p1, p2);
printf("result = ");
printPoly(result);
// 释放内存
Term *p = result;
while (p != NULL) {
Term *tmp = p;
p = p->next;
free(tmp);
}
return 0;
}
```
这个示例代码中,我们定义了一个 `Term` 结构体表示多项式的一项,包含一个系数和一个指数,还有一个指向下一项的指针。我们使用 `newTerm` 函数创建一个新的多项式项,并使用 `merge` 函数将两个多项式合并为一个,最后使用 `printPoly` 函数输出多项式。需要注意的是,我们在 `merge` 函数中创建了一个空的头节点,这样就可以很方便地处理多项式的头指针了。
你可以根据自己的需要修改这个示例代码,实现更复杂的多项式操作。