#includetypedef struct Polynome { int coef; int expo; struct Polynome* next; }Term, * Poly; void PrintPoly(Poly p); void InitPoly(Poly* p); void AddPoly(Poly pa, Poly pb); void PrintPoly(Poly p) { Term* cur = p->next; while (cur != NULL) { printf("(%d)x^%d ", cur->coef, cur->expo); if (cur->next != NULL) { printf("+ "); } cur = cur->next; } printf("nn"); } void InitPoly(Poly* p) { *p = (Poly)malloc(sizeof(Term)); if (*p == NULL) { return 0; } (*p)->next = NULL; Term* tail = *p; Term* new; int flag = 1; while (flag) { new = (Poly)malloc(sizeof(Term)); if (new == NULL) { return 0; } //(new)->next = NULL; scanf_s("%d %d", &new->coef, &new->expo); if (new->coef != 0) { tail->next = new; tail = tail->next; } else { flag = 0; tail->next = NULL; } } } void AddPoly(Poly pa, Poly pb) { Term* tail = pa; Term* p1 = pa->next; Term* p2 = pb->next; Term* temp; while (p1 != NULL && p2 != NULL) { if (p1->expo < p2->expo) { tail->next = p1; tail = p1; p1 = p1->next; } else if (p1->expo == p2->expo) { if (p1->coef + p2->coef != 0) { p1->coef += p2->coef; tail->next = p1; tail = p1; p1 = p1->next; temp = p2; p2 = p2->next; free(temp); } else { temp = p1; p1 = p1->next; free(temp); temp = p2; p2 = p2->next; free(temp); } } else { tail->next = p2; tail = p2; p2 = p2->next; } } if (p1 != NULL) { tail->next = p1; } else { tail->next = p2; } free(pb); } void Test() { printf("******按照指数次数由小到大的顺序依次添加系数和指数,输入系数为零则代表一次结束,共两次*******n"); printf("输入示例:n1 2n3 4n5 6n0 8 n"); printf("1 2n2 3n3 4n7 8n0 1 n"); Poly pa; Poly pb; InitPoly(&pa); InitPoly(&pb); printf("第一个多项式为:nn"); PrintPoly(pa); printf("第二个多项式为:nn"); PrintPoly(pb); AddPoly(pa, pb); printf("相加后的多项式为:n"); PrintPoly(pa); } int main() { Test(); return 0; }
算法思想详见注释。



