请用c++帮我写一份用链表实现一元多项式求和的代码
时间: 2023-05-26 21:03:24 浏览: 106
一元多项式 c++链表实现
5星 · 资源好评率100%
以下是使用链表实现一元多项式求和的代码,需要输入多项式项数和各项系数和指数。
#include<stdio.h>
#include<stdlib.h>
struct PolyNode{
int coef;//系数
int expon;//指数
struct PolyNode *link;//链指针
};
typedef struct PolyNode *Polynomial;
Polynomial readPoly();//读取多项式
void attach(int c, int e, Polynomial *pRear);//新建节点
Polynomial add(Polynomial p1, Polynomial p2);//多项式加法
void printPoly(Polynomial P);//输出多项式
int main(){
Polynomial P1, P2, PP;
P1 = readPoly();
P2 = readPoly();
PP = add(P1, P2);
printPoly(PP);
return 0;
}
Polynomial readPoly(){
Polynomial P, Rear, t;
int c, e, N;
scanf("%d", &N);
P = (Polynomial)malloc(sizeof(struct PolyNode));//头节点
P->link = NULL;
Rear = P;
while(N--){
scanf("%d %d", &c, &e);
attach(c, e, &Rear);//在Rear之后插入一个节点
}
t = P;
P = P->link;
free(t);//释放头节点
return P;
}
void attach(int c, int e, Polynomial *pRear){
Polynomial P;
P = (Polynomial)malloc(sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
P->link = NULL;
(*pRear)->link = P;
*pRear = P;
}
Polynomial add(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){
attach(p1->coef, p1->expon, &rear);
p1 = p1->link;
}
else if(p1->expon < p2->expon){
attach(p2->coef, p2->expon, &rear);
p2 = p2->link;
}
else{
sum = p1->coef + p2->coef;
if(sum) attach(sum, p1->expon, &rear);
p1 = p1->link;
p2 = p2->link;
}
}
for(; p1; p1 = p1->link) attach(p1->coef, p1->expon, &rear);
for(; p2; p2 = p2->link) attach(p2->coef, p2->expon, &rear);
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");
}
阅读全文