#include<stdio.h> #include<stdlib.h> typedef struct node * polynomial; struct node { int coef; //系数 int index; //指数 polynomial next; }; //读取函数 polynomial ReadPolynomial() { polynomial Rear,s,temp,p,cur; //Rear指向最后节点,s是建立链表时的节点,temp是为了free掉节点用的,p是头结点,cur是在冒泡排序时用的 int N,c,i,tmp,tmp2,n; int j = 0; p = (polynomial)malloc(sizeof(struct node));//新建头结点 p->next = NULL; Rear = p; //Rear指向最后一个节点,刚开始先指向头结点 printf("输入多项式有几个项:\n"); scanf("%d", &N); while (N--) { printf("分别输入系数和指数: "); scanf("%d %d", &c, &i); s = (polynomial)malloc(sizeof(struct node));//新建节点 s->coef = c; //系数赋值 s->index = i;//指数赋值 s->next = NULL; Rear->next = s;//指向最后一个节点的Rear连新节点 Rear = s;//Rear指向最后一个节点 } temp = p;//temp指向头结点 p = p->next;//头结点后移,现在p为第一个节点 free(temp);//释放头结点 n = CountList(p); //n是一个多项式有几项 cur = p;//cur记录头结点 //下边冒泡排序,将多项式从指数大到小排序 for (i=1; i <n; i++) { //扫描n-1次 cur = p;//下边for循环结束后,重新指向第一个节点 for (j = 0; j < n-i; j++) {//交换次数 if (cur->index < cur->next->index)//判断后交换赋值 { tmp = cur->index; tmp2 = cur->coef; cur->index = cur->next->index; cur->coef = cur->next->coef; cur->next->index = tmp; cur->next->coef = tmp2; } cur = cur->next;//向后移一个 } } return p;//返回排序后的链表的第一个节点地址 } //比较大小 int CompareIndex(polynomial p1, polynomial p2) { if (p1->index > p2->index) { return 1; } else if (p1->index < p2->index) { return 2; } else if(p1->index == p2->index) { return 3; } } //读取多项式,尾插建立相加后的链表 void AttachPolynomial(int coef, int index, polynomial *pRear) { polynomial s; s = (polynomial)malloc(sizeof(struct node)); s->coef = coef; s->index = index; s->next = NULL; (*pRear)->next = s; //pRear是指向最后的节点 (*pRear) = s; } //相加 polynomial AddPolynomial(polynomial p1, polynomial p2) { polynomial P, Rear,temp; int sum; P = (polynomial)malloc(sizeof(struct node));//头结点 Rear = P; //Rear指向最后一个结点 /*p1和p2是根据读取的指数和系数建立的两个链表,两个链表已经从大到小排好序,如果p1的指数大于p2, 那就将p1的那个节点连接到第三个节点,也就是相加后的节点,连完后p1=p1->next,向后移。其他同理。 */ while (p1&&p2) { switch (CompareIndex(p1, p2))//判断指数大小,根据CompareIndex函数返回的值执行switch { case 1: AttachPolynomial(p1->coef, p1->index, &Rear);//添加到相加链表的后边 p1 = p1->next;//后移 break; case 2: AttachPolynomial(p2->coef, p2->index, &Rear); p2 = p2->next; break; case 3: sum = p1->coef + p2->coef; AttachPolynomial(sum, p2->index, &Rear); p1 = p1->next; p2 = p2->next; break; } } for (; p1; p1 = p1->next) AttachPolynomial(p1->coef, p1->index, &Rear);//如果不为空,将剩下的节点连到相加节点 for (; p2; p2 = p2->next) AttachPolynomial(p2->coef, p2->index, &Rear); Rear->next = NULL; temp = P; P = P->next; free(temp);//释放掉相加节点的头结点 return P; } //计算链表长度 int CountList(polynomial p) { int i = 0; while (p != NULL) { i++; p = p->next; } return i; } //遍历输出 void PrintPoly(polynomial p) { int i,j; j = CountList(p); for (i = 1; i < j; i++) { printf("%dX^%d+", p->coef, p->index); p = p->next; } printf("%dX^%d", p->coef, p->index); } int main() { polynomial P1, P2,P3; P1 = ReadPolynomial();//读取并建立第一个链表 P2 = ReadPolynomial();//读取并建立第二个链表 P3=AddPolynomial(P1, P2);//读取前两个链表,建立第三个相加链表 PrintPoly(P3); system("pause"); }