C语言 用链表结构存储多项式,求两个多项式A加B的和 要求在建立多项式链表时,总是按照指数从大到小排列的
时间: 2023-10-11 10:09:04 浏览: 144
C语言:一元多项式加减法运算(链表 附答案).docx
#include<stdio.h>
#include<stdlib.h>
// 定义多项式结点结构体
typedef struct PolyNode *Polynomial;
struct PolyNode {
int coef; // 系数
int expon; // 指数
Polynomial link; // 指向下一个结点的指针
};
// 函数声明
Polynomial ReadPoly(); // 读入多项式
Polynomial Add(Polynomial A, Polynomial B); // 多项式加法
void PrintPoly(Polynomial P); // 输出多项式
int main()
{
Polynomial A, B, S;
// 读入两个多项式
A = ReadPoly();
B = ReadPoly();
// 求和
S = Add(A, B);
// 输出结果
PrintPoly(S);
return 0;
}
// 读入多项式
Polynomial ReadPoly()
{
Polynomial P, rear, t;
int c, e;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->link = NULL;
rear = P;
// 读入系数和指数,建立多项式链表
scanf("%d %d", &c, &e);
while (c != 0) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = c;
t->expon = e;
// 寻找合适的插入位置
while (rear->link && rear->link->expon > e) {
rear = rear->link;
}
// 插入结点
t->link = rear->link;
rear->link = t;
// 继续读入
scanf("%d %d", &c, &e);
}
return P;
}
// 多项式加法
Polynomial Add(Polynomial A, Polynomial B)
{
Polynomial P, rear, ta, tb, t;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->link = NULL;
rear = P;
ta = A->link;
tb = B->link;
// 合并两个多项式
while (ta && tb) {
if (ta->expon > tb->expon) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = ta->coef;
t->expon = ta->expon;
rear->link = t;
rear = t;
ta = ta->link;
} else if (ta->expon < tb->expon) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = tb->coef;
t->expon = tb->expon;
rear->link = t;
rear = t;
tb = tb->link;
} else {
int sum = ta->coef + tb->coef;
if (sum != 0) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = sum;
t->expon = ta->expon;
rear->link = t;
rear = t;
}
ta = ta->link;
tb = tb->link;
}
}
// 将剩余部分加入结果链表中
while (ta) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = ta->coef;
t->expon = ta->expon;
rear->link = t;
rear = t;
ta = ta->link;
}
while (tb) {
t = (Polynomial)malloc(sizeof(struct PolyNode));
t->coef = tb->coef;
t->expon = tb->expon;
rear->link = t;
rear = t;
tb = tb->link;
}
// 返回结果链表
rear->link = NULL;
return P;
}
// 输出多项式
void PrintPoly(Polynomial P)
{
if (!P->link) {
printf("0 0\n");
return;
}
while (P->link) {
printf("%d %d", P->link->coef, P->link->expon);
P = P->link;
if (P->link) {
printf(" ");
}
}
printf("\n");
}
阅读全文