C语言实现一元多项式加法:使用链表算法
本题可使用链表实现一元多项式的加法。具体步骤如下:
- 定义一个结构体,表示多项式中的一项,包含系数和指数。
typedef struct PolyNode {
int coef; // 系数
int expo; // 指数
struct PolyNode *next; // 指向下一项的指针
} PolyNode, *Polynomial;
- 编写输入函数,用于输入多项式的系数和指数。
Polynomial ReadPoly() {
Polynomial P, rear, t;
int coef, expo;
P = (Polynomial)malloc(sizeof(PolyNode));
P->next = NULL;
rear = P;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d %d", &coef, &expo);
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = coef;
t->expo = expo;
t->next = NULL;
rear->next = t;
rear = t;
}
return P;
}
- 编写加法函数,用于将两个多项式相加。
Polynomial Add(Polynomial P1, Polynomial P2) {
Polynomial P, rear, t;
P = (Polynomial)malloc(sizeof(PolyNode));
P->next = NULL;
rear = P;
while (P1 && P2) {
if (P1->expo > P2->expo) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = P1->coef;
t->expo = P1->expo;
t->next = NULL;
rear->next = t;
rear = t;
P1 = P1->next;
} else if (P1->expo < P2->expo) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = P2->coef;
t->expo = P2->expo;
t->next = NULL;
rear->next = t;
rear = t;
P2 = P2->next;
} else {
int sum = P1->coef + P2->coef;
if (sum != 0) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = sum;
t->expo = P1->expo;
t->next = NULL;
rear->next = t;
rear = t;
}
P1 = P1->next;
P2 = P2->next;
}
}
while (P1) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = P1->coef;
t->expo = P1->expo;
t->next = NULL;
rear->next = t;
rear = t;
P1 = P1->next;
}
while (P2) {
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = P2->coef;
t->expo = P2->expo;
t->next = NULL;
rear->next = t;
rear = t;
P2 = P2->next;
}
return P;
}
- 编写输出函数,用于输出多项式。
void PrintPoly(Polynomial P) {
if (!P) {
printf("0 0\n");
return;
}
printf("%d %d", P->coef, P->expo);
P = P->next;
while (P) {
printf(" %d %d", P->coef, P->expo);
P = P->next;
}
printf("\n");
}
- 在主函数中调用输入函数和加法函数,输出相加后的多项式。
int main() {
Polynomial P1, P2, P;
P1 = ReadPoly();
P2 = ReadPoly();
P = Add(P1, P2);
PrintPoly(P);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/lRHH 著作权归作者所有。请勿转载和采集!