用c语言数据结构实现一元多项式加法运算
时间: 2023-05-29 10:06:48 浏览: 147
#include<stdio.h>
#include<stdlib.h>
// 定义多项式结构体
typedef struct Polynomial{
int coef; // 系数
int expn; // 指数
struct Polynomial *next; // 指向下一项的指针
}Polynomial;
// 创建多项式
Polynomial* createPoly(){
Polynomial *head = (Polynomial*)malloc(sizeof(Polynomial)); // 头节点
head->next = NULL;
Polynomial *p = head; // 指针p指向头节点
int n; // 项数
printf("请输入多项式项数:");
scanf("%d", &n);
for(int i=0; i<n; i++){
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial)); // 新建节点
printf("请输入第%d项的系数和指数:", i+1);
scanf("%d%d", &node->coef, &node->expn);
node->next = NULL;
p->next = node; // 将新节点插入到链表尾部
p = node;
}
return head;
}
// 显示多项式
void displayPoly(Polynomial *poly){
Polynomial *p = poly->next; // 指针p指向第一个节点
while(p){
printf("%dX^%d", p->coef, p->expn);
p = p->next;
if(p) printf("+");
}
printf("\n");
}
// 多项式相加
Polynomial* addPoly(Polynomial *poly1, Polynomial *poly2){
Polynomial *p1 = poly1->next; // 指针p1指向第一个节点
Polynomial *p2 = poly2->next; // 指针p2指向第一个节点
Polynomial *head = (Polynomial*)malloc(sizeof(Polynomial)); // 头节点
head->next = NULL;
Polynomial *p = head; // 指针p指向头节点
while(p1 && p2){
if(p1->expn == p2->expn){ // 指数相等,系数相加
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial));
node->coef = p1->coef + p2->coef;
node->expn = p1->expn;
node->next = NULL;
p->next = node;
p = node;
p1 = p1->next;
p2 = p2->next;
}
else if(p1->expn > p2->expn){ // 第一个多项式指数大于第二个多项式指数
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial));
node->coef = p1->coef;
node->expn = p1->expn;
node->next = NULL;
p->next = node;
p = node;
p1 = p1->next;
}
else{ // 第一个多项式指数小于第二个多项式指数
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial));
node->coef = p2->coef;
node->expn = p2->expn;
node->next = NULL;
p->next = node;
p = node;
p2 = p2->next;
}
}
while(p1){ // 第一个多项式还有剩余项
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial));
node->coef = p1->coef;
node->expn = p1->expn;
node->next = NULL;
p->next = node;
p = node;
p1 = p1->next;
}
while(p2){ // 第二个多项式还有剩余项
Polynomial *node = (Polynomial*)malloc(sizeof(Polynomial));
node->coef = p2->coef;
node->expn = p2->expn;
node->next = NULL;
p->next = node;
p = node;
p2 = p2->next;
}
return head;
}
int main(){
printf("请输入第一个多项式:\n");
Polynomial *poly1 = createPoly(); // 创建第一个多项式
printf("第一个多项式为:");
displayPoly(poly1); // 显示第一个多项式
printf("请输入第二个多项式:\n");
Polynomial *poly2 = createPoly(); // 创建第二个多项式
printf("第二个多项式为:");
displayPoly(poly2); // 显示第二个多项式
Polynomial *result = addPoly(poly1, poly2); // 两个多项式相加
printf("两个多项式相加后的结果为:");
displayPoly(result); // 显示相加后的结果
return 0;
}
阅读全文