#include<iostream> #include<malloc.h> using namespace std; #define MAX 20 //多項式最多項數 typedef struct //定義存放多項式的數組類型 { float coef; //系數 int exp; //指數 }PolyArray[MAX]; typedef struct pNode //定義單鏈表結點類型 { float coef; int exp; struct pNode *next; }PolyNode; void DispPoly(PolyNode * L) //輸出多項式 { PolyNode *p=L->next; while(p!=NULL) { printf("%gX^%d",p->coef,p->exp); p=p->next; } printf("\n"); } void CreateListR(PolyNode * &L,PolyArray a,int n) //尾插法建表 { PolyNode *s,*r; int i; L=(PolyNode *)malloc(sizeof(PolyNode)); //創建頭結點 L->next=NULL; r=L; //r始終指向終端結點,開始時指向頭結點 for(i=0;i<n;i++) { s=(PolyNode *)malloc(sizeof(PolyNode)); //創建新結點 s->coef=a[i].coef; s->exp=a[i].exp; r->next=s; //將*s插入*r後 r=s; } r->next=NULL; //終端結點next域置為NULL } void Sort(PolyNode * &head) //按exp域遞減排序 { PolyNode *p=head->next,*q,*r; if(p!=NULL) //若原單鏈表中有一個或多個數據結點 { r=p->next; //r保存*p結點的後繼結點的指針 p->next=NULL; //構造只含一個數據結點的有序表 p=r; while(p!=NULL) { r=p->next; //r保存*p結點的後繼結點的指針 q=head; while(q->next!=NULL&&q->next->exp>p->exp) q=q->next; //在有序表中找插入*p的前驅結點*q p->next=q->next; //將*p插入到*q之後 q->next=p; p=r; } } } void Add(PolyNode *ha,PolyNode *hb,PolyNode *&hc) //求兩個有序集合的並 { PolyNode *pa=ha->next,*pb=hb->next,*s,*tc; float c; hc=(PolyNode *)malloc(sizeof(PolyNode)); //創建頭結點 tc=hc; while(pa!=NULL&&pb!=NULL) { if(pa->exp >pb->exp) { s=(PolyNode *)malloc(sizeof(PolyNode)); //復制結點 s->exp=pa->exp; s->coef=pa->coef; tc->next=s; tc=s; pa=pa->next; } else if(pa->exp <pb->exp) { s=(PolyNode *)malloc(sizeof(PolyNode)); //復制結點 s->exp=pb->exp; s->coef=pb->coef; tc->next=s; tc=s; pb=pb->next; } else //pa->exp==pb->exp { c=pa->coef+pb->coef; if(c!=0) //系數之和不為0時創建新結點 { s=(PolyNode *)malloc(sizeof(PolyNode)); s->exp=pa->exp; s->coef=c; tc->next=s; tc=s; } pa=pa->next; pb=pb->next; } } if(pb!=NULL) pa=pb; //復制余下的結點 while(pa!=NULL) { s=(PolyNode *)malloc(sizeof(PolyNode)); s->exp=pa->exp; s->coef=pa->coef; tc->next=s; tc=s; pa=pa->next; } tc->next=NULL; } void main() { PolyNode *ha,*hb,*hc; PolyArray a={{1.2,0},{2.5,1},{3.2,3},{-2.5,5}}; PolyArray b={{-1.2,0},{2.5,1},{3.2,3},{2.5,5},{5.4,10}}; CreateListR(ha,a,4); CreateListR(hb,b,5); printf("原多項式A:"); DispPoly(ha); printf("原多項式B:"); DispPoly(hb); Sort(ha); Sort(hb); printf("排序後多項式A:"); DispPoly(ha); printf("排序後多項式B:"); DispPoly(hb); Add(ha,hb,hc); printf("多項式相加:"); DispPoly(hc); }