- 다항식의 개수를 입력 한 후 다항식을 설명하고 두 다항식의 합을 찾으십시오.
- 기본 데모 버전이며 확장 할 수 있습니다.
- 단일 연결 목록 구현
![데이터 구조](https://img-blog.csdnimg.cn/20200713085650950.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0dvZE91Tw==,size_16,color_FFFFFF,t_70)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct PolynNode{
int coef;
int expn;
struct PolynNode *next;
}PolynNode,*PolynList;
void CreatePolyn(PolynList &L,int n){
int i;
PolynList p,q;
L=(PolynList)malloc(sizeof(PolynNode));
L->next=NULL;
q=L;
printf("成对输入%d个数据\n",n);
for(i=1;i<=n;i++){
p=(PolynList)malloc(sizeof(PolynNode));
scanf("%d%d",&p->coef,&p->expn);
q->next=p;
q=q->next;
}
p->next=NULL;
}
void PolynTraverse(PolynList L,void(*vi)(ElemType, ElemType)){
PolynList p=L->next;
while(p){
vi(p->coef, p->expn);
if(p->next){
printf(" + ");
}
p=p->next;
}
printf("\n");
}
void visit(ElemType c, ElemType e){
if(c != 0){
printf("%dX^%d",c,e);
}
}
PolynList MergeList(PolynList La, PolynList Lb){
PolynList pa, pb, pc, Lc;
pa = La->next;
pb = Lb->next;
Lc = pc = La;
while(pa&&pb){
if(pa->expn < pb->expn){
pc->next = pa;
pc = pa;
pa = pa->next;
}
else if (pa ->expn > pb->expn ){
pc->next = pb;
pc = pb;
pb = pb->next;
}
else{
pa->coef = pa->coef + pb->coef;
pc->next = pa;
pc = pa;
pa = pa->next;
pb = pb->next;
}
}
pc->next = pa ? pa:pb;
return Lc;
}
int main(){
PolynList ha,hb,hc;
int a;
printf("请输入多项式项数:\n");
scanf("%d",&a);
printf("非递减输入多项式ha, ");
CreatePolyn(ha,a);
printf("非递减输入多项式hb, ");
CreatePolyn(hb,a);
printf("\n");
printf("多项式ha :\n");
PolynTraverse(ha, visit);
printf("\n");
printf("多项式hb :\n");
PolynTraverse(hb, visit);
printf("\n");
printf("求和结果 :\n");
hc = MergeList(ha,hb);
PolynTraverse(hc, visit); }