表达式的计算(数据结构)
数据结构上的 多项式的合并计算
// sadsad.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "malloc.h" typedef struct node{ int coef; int exp; struct node *link; }PNode,*PLinkList; //以下是创建一个链表 PLinkList Creat(int n) { PLinkList p,r,list=NULL; int a,b,i; for(i=1;i<=n;i++) { scanf("%d%d",&a,&b); p=(PLinkList)malloc(sizeof(PNode)); p->coef =a; p->exp =b; p->link =NULL; if(list==NULL) list=p; else r->link =p; r=p; } return(list); } //以上是创建一个链表 PLinkList ATTACH(int co,int ex,PLinkList r) { PLinkList w; w=(PLinkList)malloc(sizeof(PNode)); w->exp =ex; w->coef =co; r->link =w; return(w); } PLinkList PADD(PLinkList A,PLinkList B) { PLinkList C; PLinkList r,p=A,q=B; int x; C=(PLinkList)malloc(sizeof(PNode)); r=C; while(p!=NULL && q!=NULL) if(p->exp ==q->exp ){ x=p->coef +q->coef ; if (x!=0) r=ATTACH(x,p->exp ,r); p=p->link ; q=q->link ; } else if (p->exp <q->exp ){ r=ATTACH(q->coef ,q->exp ,r); q=q->link ; } else{ r=ATTACH(p->coef ,p->exp ,r); p=p->link; } while(p!=NULL){ r=ATTACH(p->coef ,p->exp,r); p=p->link ; } while(q!=NULL){ r=ATTACH(q->coef ,q->exp ,r); q=q->link ; } r->link =NULL; p=C; C=C->link ; free(p); return C; } PrintPloy(PLinkList list) { PLinkList p=list; while(p!=NULL) { printf("%d,%d\n",p->coef ,p->exp ); p=p->link ; } } int main(int argc, char* argv[]) { PLinkList A,B,C; int anum,bnum; printf("输入n的值:"); scanf("%d",&anum); A=Creat(anum); PrintPloy(A); scanf("%d",&bnum); B=Creat(bnum); PrintPloy(B); C=PADD(A,B); PrintPloy(C); }
浙公网安备 33010602011771号