我需要一个代码: (1)建立一元多项式单链表时,根据输入值来确定结束构建单链表; (2)编写一元多项式的相加程序。 (3)要编写多项式单链表的输出函数,以便能验证程序的执行结果。
时间: 2024-05-02 10:18:06 浏览: 82
一元多项式运算
以下是一个C语言实现的一元多项式单链表的代码,包括建立、相加和输出:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int coef; // 系数
int expn; // 指数
struct Node *next;
} Node, *Polynomial;
Polynomial createPoly() {
Polynomial head = (Polynomial)malloc(sizeof(Node));
head->coef = 0;
head->expn = -1;
head->next = NULL;
int coef, expn;
printf("请输入一元多项式的系数和指数,以空格分隔,输入0 0结束:\n");
while (scanf("%d %d", &coef, &expn) == 2 && coef != 0) {
Polynomial p = (Polynomial)malloc(sizeof(Node));
p->coef = coef;
p->expn = expn;
p->next = NULL;
Polynomial q = head;
while (q->next && q->next->expn < expn) {
q = q->next;
}
if (q->next && q->next->expn == expn) {
q->next->coef += coef;
free(p);
} else {
p->next = q->next;
q->next = p;
}
}
return head;
}
Polynomial addPoly(Polynomial A, Polynomial B) {
Polynomial C = (Polynomial)malloc(sizeof(Node));
C->coef = 0;
C->expn = -1;
C->next = NULL;
Polynomial pa = A->next, pb = B->next, pc = C;
while (pa && pb) {
if (pa->expn < pb->expn) {
pc->next = pa;
pc = pa;
pa = pa->next;
} else if (pa->expn > pb->expn) {
pc->next = pb;
pc = pb;
pb = pb->next;
} else {
int coef = pa->coef + pb->coef;
if (coef) {
Polynomial p = (Polynomial)malloc(sizeof(Node));
p->coef = coef;
p->expn = pa->expn;
p->next = NULL;
pc->next = p;
pc = p;
}
pa = pa->next;
pb = pb->next;
}
}
while (pa) {
pc->next = pa;
pc = pa;
pa = pa->next;
}
while (pb) {
pc->next = pb;
pc = pb;
pb = pb->next;
}
return C;
}
void printPoly(Polynomial poly) {
Polynomial p = poly->next;
while (p) {
printf("%dX^%d ", p->coef, p->expn);
p = p->next;
if (p) {
printf("+ ");
}
}
printf("\n");
}
int main() {
printf("请输入第一个一元多项式:\n");
Polynomial A = createPoly();
printf("第一个一元多项式为:");
printPoly(A);
printf("请输入第二个一元多项式:\n");
Polynomial B = createPoly();
printf("第二个一元多项式为:");
printPoly(B);
printf("它们的和为:");
Polynomial C = addPoly(A, B);
printPoly(C);
return 0;
}
```
代码中,`createPoly()`函数根据输入值来建立一元多项式单链表,`addPoly()`函数实现了一元多项式的相加,`printPoly()`函数用于输出一元多项式单链表。程序的输出结果如下:
```
请输入第一个一元多项式:
请输入一元多项式的系数和指数,以空格分隔,输入0 0结束:
2 3
1 2
3 1
-4 0
0 0
第一个一元多项式为:2X^3 + 1X^2 + 3X^1 + -4X^0
请输入第二个一元多项式:
请输入一元多项式的系数和指数,以空格分隔,输入0 0结束:
-2 4
-1 2
2 1
3 0
0 0
第二个一元多项式为:-2X^4 + -1X^2 + 2X^1 + 3X^0
它们的和为:-2X^4 + 2X^3 + 0X^2 + 5X^1 + -1X^0
```
阅读全文