建立一个多项式,并对多项式按照指数排序#include "Poly.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> void CreatePoly(pList list) { pList ptr = list; ptr->next = NULL; char c; printf("Input Y/N/n"); c = getchar(); while(c != 'N' && c != 'n') { printf("c is %c/n",c); pList p = (pList) malloc(sizeof(List)); if(!p) { printf("Memory allocate Error/n"); exit(1); } p->next = NULL; printf("/nInput coef expn!/n"); float coef,expn; scanf("%f %d",&p->data.coef,&p->data.expn); ptr->next = p; ptr = p; getchar(); c = getchar(); } } void Print(pList list) { pList ptr = list->next; while(ptr) { printf("%5.2f %d/n",ptr->data.coef,ptr->data.expn); ptr = ptr->next; } } //查找head链表中指数《=expn的最后一个结点 pList find(pList head,int expn) { if(head->next == NULL) { printf("List Is Null/n"); return NULL; } pList p = head,q = head->next; if(expn <= q->data.expn) return p; while(q&&q->data.expn<=expn) { p = q; q = q->next; } if(q == NULL) return p; else return q; } //ptr之后插入temp void InsertList(pList ptr,pList temp) { assert(ptr != NULL && temp != NULL); temp->next = ptr->next; ptr->next = temp; } pList OrderList(pList head) { if(head->next == NULL) { printf("List Is Null/n"); return NULL; } pList p = head->next, q = p->next; pList ptr = (pList)malloc(sizeof(List)); if(!ptr) { printf("Memory allocate Error/n"); exit(1); } ptr->next = NULL; p->next = ptr->next; ptr->next = p; p = q; q = q->next; while(p) { pList temp = find(ptr,p->data.expn); InsertList(temp,p); p = q; if(q == NULL) { p = NULL; break; } q = q->next; } return ptr; } void main() { pList list = (pList)malloc(sizeof(List)); CreatePoly(list); Print(list); printf("排序后的链表为:/n"); pList newList = (pList)malloc(sizeof(List)); newList = OrderList(list); Print(newList); }