C语言实现一元多项式加法运算
#include <stdio.h> #include <stdlib.h>
// 定义多项式结构体 typedef struct PolyNode *Polynomial; struct PolyNode { int coef; // 系数 int expon; // 指数 Polynomial link; // 指向下一个节点的指针 };
// 多项式求和 Polynomial PolyAdd(Polynomial P1, Polynomial P2) { Polynomial front, rear, temp; int sum;
// 创建一个头结点
rear = (Polynomial) malloc(sizeof(struct PolyNode));
front = rear;
while (P1 && P2) {
if (P1->expon > P2->expon) {
// P1 的指数大于 P2 的指数,将 P1 的节点添加到结果中
temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = P1->coef;
temp->expon = P1->expon;
rear->link = temp;
rear = temp;
P1 = P1->link;
} else if (P1->expon < P2->expon) {
// P2 的指数大于 P1 的指数,将 P2 的节点添加到结果中
temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = P2->coef;
temp->expon = P2->expon;
rear->link = temp;
rear = temp;
P2 = P2->link;
} else {
// P1 和 P2 的指数相等,将它们的系数相加
sum = P1->coef + P2->coef;
if (sum) {
temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = sum;
temp->expon = P1->expon;
rear->link = temp;
rear = temp;
}
P1 = P1->link;
P2 = P2->link;
}
}
// 将 P1 或 P2 中剩余的节点添加到结果中
for (; P1; P1 = P1->link) {
temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = P1->coef;
temp->expon = P1->expon;
rear->link = temp;
rear = temp;
}
for (; P2; P2 = P2->link) {
temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = P2->coef;
temp->expon = P2->expon;
rear->link = temp;
rear = temp;
}
rear->link = NULL;
temp = front;
front = front->link;
free(temp);
return front;
}
// 输出多项式 void PrintPoly(Polynomial P) { int flag = 0; // 是否是多项式的第一项
if (!P) {
printf("0 0\n");
return;
}
while (P) {
if (!flag) {
flag = 1;
} else {
printf(" ");
}
printf("%d %d", P->coef, P->expon);
P = P->link;
}
printf("\n");
}
int main() { // 创建多项式 P1 Polynomial P1, P1rear; int n; scanf("%d", &n); P1 = (Polynomial) malloc(sizeof(struct PolyNode)); P1->link = NULL; P1rear = P1;
int coef, expon;
while (n--) {
scanf("%d %d", &coef, &expon);
Polynomial temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = coef;
temp->expon = expon;
temp->link = NULL;
P1rear->link = temp;
P1rear = temp;
}
// 创建多项式 P2
Polynomial P2, P2rear;
scanf("%d", &n);
P2 = (Polynomial) malloc(sizeof(struct PolyNode));
P2->link = NULL;
P2rear = P2;
while (n--) {
scanf("%d %d", &coef, &expon);
Polynomial temp = (Polynomial) malloc(sizeof(struct PolyNode));
temp->coef = coef;
temp->expon = expon;
temp->link = NULL;
P2rear->link = temp;
P2rear = temp;
}
// 求和并输出结果
Polynomial sum = PolyAdd(P1->link, P2->link);
PrintPoly(sum);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/lRHI 著作权归作者所有。请勿转载和采集!