c语言 求两个多项式的和(1)编写函数实现一个多项式的输入,先输入非零项的个数,再输入每一对非零项系数和指数,返回多项式链表的头指针。(2)编写函数实现两个多项式相加,返回结果多项式链表的头指针。(3)编写函数输出和的每一对非零项系数和指数(4)在main函数中分别调用上述函数。
时间: 2024-02-25 15:54:57 浏览: 83
下面是实现这些功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式项的结构体
typedef struct PolyNode {
int coef; // 系数
int expon; // 指数
struct PolyNode *next;
} PolyNode, *Polynomial;
// 从标准输入读入多项式,返回多项式链表的头指针
Polynomial read_poly() {
int n; // 非零项的个数
scanf("%d", &n);
Polynomial head = (Polynomial)malloc(sizeof(PolyNode));
head->next = NULL;
Polynomial tail = head;
while (n--) {
int coef, expon;
scanf("%d %d", &coef, &expon);
if (coef != 0) {
Polynomial node = (Polynomial)malloc(sizeof(PolyNode));
node->coef = coef;
node->expon = expon;
node->next = NULL;
tail->next = node;
tail = node;
}
}
return head;
}
// 将两个多项式相加,返回结果多项式链表的头指针
Polynomial add_poly(Polynomial p1, Polynomial p2) {
Polynomial head = (Polynomial)malloc(sizeof(PolyNode));
head->next = NULL;
Polynomial tail = head;
while (p1 && p2) {
if (p1->expon > p2->expon) {
tail->next = p1;
p1 = p1->next;
} else if (p1->expon < p2->expon) {
tail->next = p2;
p2 = p2->next;
} else {
int coef = p1->coef + p2->coef;
if (coef != 0) {
Polynomial node = (Polynomial)malloc(sizeof(PolyNode));
node->coef = coef;
node->expon = p1->expon;
node->next = NULL;
tail->next = node;
tail = node;
}
p1 = p1->next;
p2 = p2->next;
}
}
if (p1) {
tail->next = p1;
}
if (p2) {
tail->next = p2;
}
return head->next;
}
// 输出多项式
void print_poly(Polynomial poly) {
if (poly == NULL) {
printf("0 0\n");
return;
}
while (poly) {
printf("%d %d", poly->coef, poly->expon);
poly = poly->next;
if (poly) {
printf(" ");
}
}
printf("\n");
}
int main() {
// 输入两个多项式
printf("请输入第一个多项式(非零项的个数,每一对非零项系数和指数):\n");
Polynomial p1 = read_poly();
printf("请输入第二个多项式(非零项的个数,每一对非零项系数和指数):\n");
Polynomial p2 = read_poly();
// 计算两个多项式的和
Polynomial sum = add_poly(p1, p2);
// 输出结果
printf("两个多项式的和为:\n");
print_poly(sum);
// 释放内存
free(p1);
free(p2);
free(sum);
return 0;
}
```
阅读全文