c语言 求两个多项式的和(1)编写函数实现一个多项式的输入,返回多项式链表的头指针。(2)编写函数实现两个多项式相加,返回结果多项式链表的头指针。(3)编写函数输出一个多项式的二元组序列。(4)在main函数中分别调用上述函数。(5)先输入非零项的个数,再输入每一对非零项系数和指数。(6)输出和的每一对非零项系数和指数
时间: 2024-02-25 11:54:45 浏览: 69
好的,我会根据您的要求进行回答,下面是代码实现:
```
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的结构体
typedef struct PolyNode {
int coef; // 系数
int expon; // 指数
struct PolyNode* next;
} PolyNode, *Polynomial;
// 多项式输入函数
Polynomial readPoly() {
Polynomial p, rear, t;
int c, e;
p = (Polynomial)malloc(sizeof(PolyNode));
p->next = NULL;
rear = p;
scanf("%d %d", &c, &e);
while (c != 0) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = c;
t->expon = e;
rear->next = t;
rear = t;
scanf("%d %d", &c, &e);
}
rear->next = NULL;
return p;
}
// 多项式相加函数
Polynomial addPoly(Polynomial p1, Polynomial p2) {
Polynomial front, rear, temp;
int sum;
rear = (Polynomial)malloc(sizeof(PolyNode));
front = rear;
while (p1 && p2) {
if (p1->expon == p2->expon) {
sum = p1->coef + p2->coef;
if (sum) {
temp = (Polynomial)malloc(sizeof(PolyNode));
temp->coef = sum;
temp->expon = p1->expon;
rear->next = temp;
rear = temp;
}
p1 = p1->next;
p2 = p2->next;
}
else if (p1->expon > p2->expon) {
temp = (Polynomial)malloc(sizeof(PolyNode));
temp->coef = p1->coef;
temp->expon = p1->expon;
rear->next = temp;
rear = temp;
p1 = p1->next;
}
else {
temp = (Polynomial)malloc(sizeof(PolyNode));
temp->coef = p2->coef;
temp->expon = p2->expon;
rear->next = temp;
rear = temp;
p2 = p2->next;
}
}
while (p1) {
temp = (Polynomial)malloc(sizeof(PolyNode));
temp->coef = p1->coef;
temp->expon = p1->expon;
rear->next = temp;
rear = temp;
p1 = p1->next;
}
while (p2) {
temp = (Polynomial)malloc(sizeof(PolyNode));
temp->coef = p2->coef;
temp->expon = p2->expon;
rear->next = temp;
rear = temp;
p2 = p2->next;
}
rear->next = NULL;
temp = front;
front = front->next;
free(temp);
return front;
}
// 多项式输出函数
void printPoly(Polynomial p) {
if (p) {
printf("%d %d", p->coef, p->expon);
p = p->next;
while (p) {
printf(" %d %d", p->coef, p->expon);
p = p->next;
}
}
printf("\n");
}
int main() {
Polynomial p1, p2, p;
int n1, n2;
printf("请输入第一个多项式的非零项个数:");
scanf("%d", &n1);
printf("请输入第一个多项式每一项的系数和指数:");
p1 = readPoly();
printf("第一个多项式为:");
printPoly(p1);
printf("请输入第二个多项式的非零项个数:");
scanf("%d", &n2);
printf("请输入第二个多项式每一项的系数和指数:");
p2 = readPoly();
printf("第二个多项式为:");
printPoly(p2);
p = addPoly(p1, p2);
printf("相加后的多项式为:");
printPoly(p);
return 0;
}
```
这段代码实现了多项式的输入、相加和输出功能,您只需要输入非零项的个数以及每一项的系数和指数,就可以得到两个多项式的和的每一对非零项系数和指数。
阅读全文