(1)建立一元多项式单链表时,根据输入值来确定结束构建单链表; (2)编写一元多项式的相加程序。 (3)要编写多项式单链表的输出函数,以便能验证程序的执行结果。使用c语言
时间: 2024-05-11 07:13:41 浏览: 49
以下是使用C语言实现一元多项式单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Term {
int coef; // 系数
int expn; // 指数
struct Term *next; // 下一项
} Term, *Polynomial;
void createPolyn(Polynomial *pPoly) {
int coef, expn;
*pPoly = (Polynomial)malloc(sizeof(Term));
(*pPoly)->next = NULL;
printf("请输入一元多项式,系数和指数以空格分隔,以0 0结束\n");
while (1) {
scanf("%d %d", &coef, &expn);
if (coef == 0 && expn == 0) {
break;
}
Term *pTerm = (Term*)malloc(sizeof(Term));
pTerm->coef = coef;
pTerm->expn = expn;
pTerm->next = NULL;
Term *p = *pPoly;
while (p->next && p->next->expn < expn) {
p = p->next;
}
if (p->next && p->next->expn == expn) {
p->next->coef += coef;
if (p->next->coef == 0) {
Term *q = p->next;
p->next = q->next;
free(q);
}
} else {
pTerm->next = p->next;
p->next = pTerm;
}
}
}
void addPolyn(Polynomial p1, Polynomial p2, Polynomial *pSum) {
*pSum = (Polynomial)malloc(sizeof(Term));
(*pSum)->next = NULL;
Term *p = (*pSum);
Term *pTerm1 = p1->next;
Term *pTerm2 = p2->next;
while (pTerm1 && pTerm2) {
if (pTerm1->expn < pTerm2->expn) {
p->next = pTerm1;
pTerm1 = pTerm1->next;
} else if (pTerm1->expn > pTerm2->expn) {
p->next = pTerm2;
pTerm2 = pTerm2->next;
} else {
int coef = pTerm1->coef + pTerm2->coef;
if (coef != 0) {
Term *pTerm = (Term*)malloc(sizeof(Term));
pTerm->coef = coef;
pTerm->expn = pTerm1->expn;
p->next = pTerm;
pTerm1 = pTerm1->next;
pTerm2 = pTerm2->next;
} else {
pTerm1 = pTerm1->next;
pTerm2 = pTerm2->next;
}
}
p = p->next;
}
p->next = pTerm1 ? pTerm1 : pTerm2;
}
void printPolyn(Polynomial poly) {
Term *p = poly->next;
while (p) {
printf("%dX^%d", p->coef, p->expn);
p = p->next;
if (p) {
printf("+");
}
}
printf("\n");
}
int main() {
Polynomial poly1, poly2, polySum;
createPolyn(&poly1);
createPolyn(&poly2);
addPolyn(poly1, poly2, &polySum);
printf("多项式1:\n");
printPolyn(poly1);
printf("多项式2:\n");
printPolyn(poly2);
printf("多项式1 + 多项式2 = :\n");
printPolyn(polySum);
return 0;
}
```
使用示例:
```
请输入一元多项式,系数和指数以空格分隔,以0 0结束
1 2
2 1
3 0
0 0
请输入一元多项式,系数和指数以空格分隔,以0 0结束
-1 2
2 1
1 0
0 0
多项式1:
1X^2+2X^1+3X^0
多项式2:
-1X^2+2X^1+1X^0
多项式1 + 多项式2 = :
2X^1+4X^0
```
阅读全文