C语言实现一元多项式加法运算 - 代码详解
#include <stdio.h> #include <stdlib.h>
struct node { int coefficient; // 系数 int exponent; // 指数 struct node *next; // 指向下一个节点 };
struct node *create_poly(); // 创建多项式 void print_poly(struct node *poly); // 输出多项式 struct node *add_poly(struct node *poly1, struct node *poly2); // 多项式加法
int main() { struct node *poly1, *poly2, *sum;
printf("输入第一个多项式:\n");
poly1 = create_poly();
printf("\n输入第二个多项式:\n");
poly2 = create_poly();
sum = add_poly(poly1, poly2);
printf("\n第一个多项式:\n");
print_poly(poly1);
printf("\n第二个多项式:\n");
print_poly(poly2);
printf("\n它们的和:\n");
print_poly(sum);
return 0;
}
struct node *create_poly() { struct node *head, *p, *q; int coefficient, exponent;
head = (struct node *)malloc(sizeof(struct node));
p = head;
printf("请输入系数和指数,输入-1表示结束:\n");
while (1) {
scanf("%d%d", &coefficient, &exponent);
if (coefficient == -1 && exponent == -1) {
break;
}
q = (struct node *)malloc(sizeof(struct node));
q->coefficient = coefficient;
q->exponent = exponent;
p->next = q;
p = q;
}
p->next = NULL;
return head->next;
}
void print_poly(struct node *poly) { while (poly != NULL) { printf("%dX^%d", poly->coefficient, poly->exponent); poly = poly->next; if (poly != NULL) { printf("+"); } } }
struct node *add_poly(struct node *poly1, struct node *poly2) { struct node *head, *p, *q, *sum;
head = (struct node *)malloc(sizeof(struct node));
p = poly1;
q = poly2;
sum = head;
while (p != NULL && q != NULL) {
if (p->exponent < q->exponent) {
sum->next = p;
p = p->next;
} else if (p->exponent > q->exponent) {
sum->next = q;
q = q->next;
} else {
int coefficient = p->coefficient + q->coefficient;
if (coefficient != 0) {
struct node *node = (struct node *)malloc(sizeof(struct node));
node->coefficient = coefficient;
node->exponent = p->exponent;
sum->next = node;
p = p->next;
q = q->next;
sum = sum->next;
} else {
p = p->next;
q = q->next;
}
}
if (p != NULL) {
sum->next = p;
} else {
sum->next = q;
}
}
return head->next;
}
原文地址: https://www.cveoy.top/t/topic/lRHj 著作权归作者所有。请勿转载和采集!