算法与数据结构 多项式相加.docVIP

  • 20
  • 0
  • 约3.65千字
  • 约 7页
  • 2017-12-22 发布于河南
  • 举报
算法与数据结构 多项式相加

算法与数据结构 多项式相加 #include stdio.h #include malloc.h typedef struct node {float coef;/*序数*/ int expn;/*指数*/ struct node *next;/*指向下一个结点的指针*/ } PolyNode; void InitList(PolyNode *L)/*初始化多项式单链表*/ { L=(PolyNode *)malloc(sizeof(PolyNode)); /*建立头结点*/ L-next=NULL; } int GetLength(PolyNode *L) /*求多项式单链表的长度*/ { int i=0; PolyNode *p=L-next; while (p!=NULL) /*扫描单链表L,用i累计结点个数*/ { i++;p=p-next; } return i; } PolyNode *GetElem(PolyNode *L,int i) /*返回多项式单链表中第i个结点的指针*/ { int j=1; PolyNode *p=L-next; if (i1 || iGetLength(L)) return NULL; while (ji) /*沿next域找第i个结点*/ { p=p-next;j++; } return p; } PolyNode *Locate(PolyNode *L,float c,int e) /*在多项式单链表中按值查找*/ { PolyNode *p=L-next; while (p!=NULL (p-coef!=c ||p-expn!=e)) p=p-next; return p; } int InsElem(PolyNode *L,float c,int e,int i) /*在多项式单链表中插入一个结点*/ { int j=1; PolyNode *p=L,*s; s=(PolyNode *)malloc(sizeof(PolyNode)); s-coef=c;s-expn=e;s-next=NULL; if (i1 || iGetLength(L)+1) return 0; while (ji) /*查找第i-1个结点*p*/ { p=p-next;j++; } s-next=p-next; p-next=s; return 1; } int DelElem(PolyNode *L,int i) /*在多项式单链表中删除一个结点*/ { int j=1; PolyNode *p=L,*q; if (i1 || iGetLength(L)) return 0; while (ji) /*在单链表中查找第i-1个结点,由p指向它*/ { p=p-next;j++; } q=p-next; /*q指向被删结点*/ p-next=q-next; /*删除*q结点*/ free(q); return 1; } void DispList(PolyNode *L) /*输出多项式单链表的元素值*/ { PolyNode *p=L-next; while (p!=NULL) { printf((%g,%d) ,p-coef,p-expn); p=p-next; } printf(\n); } void CreaPolyList(PolyNode *L,float C[],int E[],int n) { int i; InitList(L); for (i=0;in;i++) InsElem(L,C[i],E[i],i+1); } void SortPloy(PolyNode *L) /*对L的多项式单链表按expn域递增排序*/ { PolyNode *p=L-next,*q,*pre; L-next=NULL; while (p!=NULL) { if (L-next==NULL) /*处理第1个结点*/ { L-next=p;p=p-next; L-next-next=NULL; } else /*处理其余结点*/ { pre=L;q=pre-next; while (q!=NULL p-expnq-expn) /*找q-expn刚大于或等于p-expn的结点*q的前驱结点*pre*/ { pre=q;q=q-next; } q=p-next; /*在*pre结点之后插入*p*/ p-next=pre-next; pre-next=p

文档评论(0)

1亿VIP精品文档

相关文档