代码如下:
/*************************************************************************> File Name: AddPoly.c> Author: YueBo> Mail: yuebowhu@163.com> Created Time: 2016年12月17日 星期六 13时00分35秒************************************************************************/#include<stdio.h>
#include <malloc.h>typedef struct PolyNode* Polynomial;
struct PolyNode {int coef;int expon;Polynomial link;
};void Print(Polynomial P)
{int i = 0;if (!P) {printf("0 0");} else {while (P) {if (i) {printf(" ");}printf("%d %d", P->coef, P->expon);P = P->link;++i;}}
}int Compare(int a, int b)
{if (a > b) {return 1;}if (a < b) {return -1;}if (a == b) {return 0;}
}void Attach(int coef, int expon, Polynomial* PtrRear)
{Polynomial P;P = (Polynomial)malloc(sizeof(struct PolyNode));P->coef = coef;P->expon = expon;P->link = NULL;(*PtrRear)->link = P;*PtrRear = P;
}Polynomial PolyAdd(Polynomial P1, Polynomial P2)
{Polynomial front, rear, temp;int sum;// 为i方便表头插入,先产生一个临时空结点作为结果多项式的链表头 rear = (Polynomial)malloc(sizeof(struct PolyNode)); front = rear;while (P1 && P2) {switch (Compare(P1->expon, P2->expon)) {case 1:Attach(P1->coef, P1->expon, &rear);P1 = P1->link;break;case -1:Attach(P2->coef, P2->expon, &rear);P2 = P2->link;break;case 0:sum = P1->coef + P2->coef;if (sum) {Attach(sum, P1->expon, &rear);}P1 = P1->link;P2 = P2->link;break;}}//将未处理完的另一个多项式的所有结点依次复制到结果链表中for (; P1; P1 = P1->link) {Attach(P1->coef, P1->expon, &rear);}for (; P2; P2 = P2->link) {Attach(P2->coef, P2->expon, &rear);}rear->link = NULL;temp = front;front = front->link; //令front指向多项式的第一项mZ free(temp); //释放掉临时空表头结点return front;
}Polynomial PolyMult(Polynomial P1, Polynomial P2)
{Polynomial P = NULL, temp1, temp2, copyP2;copyP2 = P2;temp1 = (Polynomial)malloc(sizeof(struct PolyNode));while (P1) {P2 = copyP2;while (P2) {temp1->coef = P1->coef * P2->coef;temp1->expon = P1->expon + P2->expon;temp1->link = NULL;temp2 = P;P = PolyAdd(P, temp1);free(temp2);P2 = P2->link;}P1 = P1->link;}free(temp1);return P;
}int main()
{Polynomial P1 = NULL, P2 = NULL, sumP = NULL, multP = NULL, front = NULL, rear = NULL, tempNode = NULL;int N1, N2;int i;int temp_coef, temp_expon;scanf("%d", &N1);for (i = 0; i < N1; i++) {scanf("%d%d", &temp_coef, &temp_expon);tempNode = (Polynomial)malloc(sizeof(struct PolyNode));tempNode->coef = temp_coef;tempNode->expon = temp_expon;tempNode->link = NULL;if (i == 0) {P1 = rear = tempNode;} else {rear->link = tempNode;rear = rear->link;}}scanf("%d", &N2);for (i = 0; i < N2; i++) {scanf("%d%d", &temp_coef, &temp_expon);tempNode = (Polynomial)malloc(sizeof(struct PolyNode));tempNode->coef = temp_coef;tempNode->expon = temp_expon;tempNode->link = NULL;if (i == 0) {P2 = rear = tempNode;} else {rear->link = tempNode;rear = rear->link;}}multP = PolyMult(P1, P2);sumP = PolyAdd(P1, P2);Print(multP);printf("\n");Print(sumP);return 0;
}