#include <stdio.h> #include <stdlib.h> typedef struct Node //一个项节点 { int modulus; //系数 int cover; //幂 struct Node* next; }List; void creatList(List *&l) //创建多项式链表 { List* r; List* s; int n; l = (List*)malloc(sizeof(Node)); r = l; printf("多项式的项数:"); scanf("%d",&n); printf("依次输入%d个项的系数和幂/n",n); while(n--) { s = (List*)malloc(sizeof(List)); scanf("%d",&s->modulus); scanf("%d",&s->cover); r->next = s; r = s; } r->next = NULL; } void printList(List *l) //打印多项式 { List* r; r = l->next; while(r!=NULL) { printf("%dy^%d",r->modulus,r->cover); if(r->next!=NULL) printf("+"); r = r->next; } printf("/n"); } int cmpList(List *l1,List *l2) //比较幂 { if(l1->cover==l2->cover) { return 0; } else if(l1->cover>l2->cover) { return 1; } return -1; } void sortList(List*& l) //将多项式链表按幂降序排列 { List* r; List* p; List* q; List* s = NULL; r = l; p = r->next; q = p->next; while(q!=s) { while(q!=s) { if(cmpList(p,q)==-1) { r->next = q; p->next = q->next; q->next = p; r = q; p = r->next; q = p->next; } else { r = p; p = r->next; q = p->next; } } s = p; r = l; p = r->next; q = p->next; } } void addList(List *l1,List *l2,List *&l3)//多项式链表相加 { l3 = (List*)malloc(sizeof(List)); List *r = l1->next; List *p = l2->next; List *q = l3; List *s; while(r&&p) { switch(cmpList(r,p)) { case 1: s = (List*)malloc(sizeof(List)); s->modulus = r->modulus; s->cover = r->cover; q->next = s; q = s; q->next = NULL; r = r->next; break; case -1: s = (List*)malloc(sizeof(List)); s->modulus = p->modulus; s->cover = p->cover; q->next = s; q = s; q->next = NULL; p = p->next; break; case 0: s = (List*)malloc(sizeof(List)); if(r->modulus-p->modulus==0) { r = r->next; p = p->next; free(s); break; } else { s->modulus = r->modulus+p->modulus; s->cover = r->cover; q->next = s; q = s; q->next = NULL; r = r->next; p = p->next; break; } } } while(r) { s = (List*)malloc(sizeof(List)); s->modulus = r->modulus; s->cover = r->cover; q->next = s; q = s; q->next = NULL; r = r->next; } while(p) { s = (List*)malloc(sizeof(List)); s->modulus = p->modulus; s->cover = p->cover; q->next = s; q = s; q->next = NULL; q = q->next; } } int main() { List *l1; List *l2; List *l3; creatList(l1); sortList(l1); printList(l1); creatList(l2); sortList(l2); printList(l2); addList(l1,l2,l3); printf("相加后结果为:/n"); printList(l3); free(l1); free(l2); free(l3); }