编程实现一元多项式的加法运算。第一个一元多项式A; 第二个一元多项式B。 以(0,0)作为输入结束。多项式A和多项式B的和。数据结构 
时间: 2023-05-29 21:06:02 浏览: 27
可以使用链表来存储一元多项式。
具体实现步骤如下:
1. 定义一个结构体来表示一项多项式,包括系数和指数两个成员变量。
2. 定义一个链表节点结构体,包括一项多项式和一个指向下一个节点的指针。
3. 定义一个函数来创建一项多项式的链表,输入系数和指数,返回一个链表头指针。
4. 定义一个函数来打印一元多项式。
5. 定义一个函数来实现一元多项式的加法运算,输入两个链表头指针,返回一个链表头指针。
6. 在主函数中,循环输入一元多项式的系数和指数,直到输入(0,0)为止。然后调用创建链表函数,分别创建两个一元多项式的链表。接着调用加法运算函数,计算并打印结果。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 一项多项式结构体
struct PolyTerm {
int coef; // 系数
int exp; // 指数
};
// 链表节点结构体
struct Node {
struct PolyTerm term; // 一项多项式
struct Node* next; // 下一个节点的指针
};
// 创建一项多项式的链表,输入系数和指数,返回一个链表头指针
struct Node* createPoly(int coef, int exp) {
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->term.coef = coef;
head->term.exp = exp;
head->next = NULL;
return head;
}
// 打印一元多项式
void printPoly(struct Node* head) {
struct Node* p = head;
while (p != NULL) {
printf("%d*x^%d", p->term.coef, p->term.exp);
p = p->next;
if (p != NULL && p->term.coef > 0) {
printf("+");
}
}
printf("\n");
}
// 实现一元多项式的加法运算,输入两个链表头指针,返回一个链表头指针
struct Node* addPoly(struct Node* head1, struct Node* head2) {
struct Node* p1 = head1;
struct Node* p2 = head2;
struct Node* head3 = (struct Node*)malloc(sizeof(struct Node));
struct Node* p3 = head3;
while (p1 != NULL && p2 != NULL) {
if (p1->term.exp > p2->term.exp) {
p3->term = p1->term;
p1 = p1->next;
} else if (p1->term.exp < p2->term.exp) {
p3->term = p2->term;
p2 = p2->next;
} else {
p3->term.coef = p1->term.coef + p2->term.coef;
if (p3->term.coef != 0) {
p3->term.exp = p1->term.exp;
p1 = p1->next;
p2 = p2->next;
} else {
p1 = p1->next;
p2 = p2->next;
continue;
}
}
p3->next = (struct Node*)malloc(sizeof(struct Node));
p3 = p3->next;
p3->next = NULL;
}
while (p1 != NULL) {
p3->term = p1->term;
p1 = p1->next;
p3->next = (struct Node*)malloc(sizeof(struct Node));
p3 = p3->next;
p3->next = NULL;
}
while (p2 != NULL) {
p3->term = p2->term;
p2 = p2->next;
p3->next = (struct Node*)malloc(sizeof(struct Node));
p3 = p3->next;
p3->next = NULL;
}
p3 = head3;
head3 = head3->next;
free(p3);
return head3;
}
int main() {
struct Node* head1 = NULL;
struct Node* head2 = NULL;
struct Node* head3 = NULL;
int coef, exp;
printf("Input polynomial A:(coef, exp)\n");
scanf("%d%d", &coef, &exp);
head1 = createPoly(coef, exp);
while (coef != 0 || exp != 0) {
scanf("%d%d", &coef, &exp);
if (coef == 0 && exp == 0) {
break;
}
struct Node* p = createPoly(coef, exp);
p->next = head1->next;
head1->next = p;
}
printf("Input polynomial B:(coef, exp)\n");
scanf("%d%d", &coef, &exp);
head2 = createPoly(coef, exp);
while (coef != 0 || exp != 0) {
scanf("%d%d", &coef, &exp);
if (coef == 0 && exp == 0) {
break;
}
struct Node* p = createPoly(coef, exp);
p->next = head2->next;
head2->next = p;
}
printf("Polynomial A: ");
printPoly(head1);
printf("Polynomial B: ");
printPoly(head2);
head3 = addPoly(head1, head2);
printf("Polynomial A+B: ");
printPoly(head3);
return 0;
}
```
相关推荐













