02-線性結構2 一元多項式的乘法與加法運算 (20 分)
阿新 • • 發佈:2018-12-12
設計函式分別求兩個一元多項式的乘積與和。
輸入格式:
輸入分2行,每行分別先給出多項式非零項的個數,再以指數遞降方式輸入一個多項式非零項係數和指數(絕對值均為不超過1000的整數)。數字間以空格分隔。
輸出格式:
輸出分2行,分別以指數遞降方式輸出乘積多項式以及和多項式非零項的係數和指數。數字間以空格分隔,但結尾不能有多餘空格。零多項式應輸出0 0
。
輸入樣例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
輸出樣例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1 5 20 -4 4 -5 2 9 1 -2 0
#include<cstdio> #include<cstdlib> typedef struct Node *Polynomial; struct Node{ int coef; int exp; Polynomial link; }; void attach(int coef, int exp, Polynomial *pRear){ Polynomial p; p = (Polynomial)malloc(sizeof(struct Node)); p->coef = coef; p->exp = exp; (*pRear)->link = p; *pRear = p; } Polynomial read(){ int n, a, b; Polynomial Rear, p, t; p = (Polynomial)malloc(sizeof(struct Node)); p->link = NULL; Rear = p; scanf("%d", &n); while(n--){ scanf("%d%d", &a, &b); attach(a, b, &Rear); } Rear->link = NULL; t = p; p = p->link; free(t); return p; } Polynomial add(Polynomial p1, Polynomial p2){ Polynomial p, t1, t2, Rear, t; t1 = p1; t2 = p2; p = (Polynomial)malloc(sizeof(struct Node)); Rear = p; p->link = NULL; while(t1 && t2){ if(t1->exp == t2->exp){ int c = t1->coef + t2->coef; if(c)attach(c, t1->exp, &Rear); t1 = t1->link; t2 = t2->link; }else if(t1->exp < t2->exp){ Rear->link = t2; Rear = t2; t2 = t2->link; }else{ Rear->link = t1; Rear = t1; t1 = t1->link; } } while(t1){ Rear->link = t1; Rear = t1; t1 = t1->link; } while(t2){ Rear->link = t2; Rear = t2; t2 = t2->link; } Rear->link = NULL; t = p; p = p->link; free(t); return p; } Polynomial multi(Polynomial p1, Polynomial p2){ Polynomial p, t1, t2, Rear, temp; int e, c; if(!p1 || !p2)return NULL; p = (Polynomial)malloc(sizeof(struct Node)); p->link = NULL; Rear = p; t1 = p1; t2 = p2; while(t2){ e = t1->exp + t2->exp; c = t1->coef * t2->coef; attach(c, e, &Rear); t2 = t2->link; } t1 = t1->link; while(t1){ t2 = p2; Rear = p; while(t2){ e = t1->exp + t2->exp; c = t1->coef * t2->coef; while(Rear->link && Rear->link->exp > e)Rear = Rear->link; if(Rear->link && Rear->link->exp == e){ if(Rear->link->coef + c){ Rear->link->coef += c; }else{ temp = Rear->link; Rear->link = temp->link; free(temp); } }else{ temp = (Polynomial)malloc(sizeof(struct Node)); temp->exp = e; temp->coef = c; temp->link = Rear->link; Rear->link = temp; } t2 = t2->link; } t1 = t1->link; } Rear->link->link = NULL; temp = p; p = p->link; free(temp); return p; } void print(Polynomial p){ Polynomial t = p; if(t == NULL){ printf("0 0\n"); return; } else{ while(t){ if(t->link != NULL)printf("%d %d ", t->coef, t->exp); else printf("%d %d\n", t->coef, t->exp); t = t->link; } } } int main(){ Polynomial p1, p2, p3, p4; p1 = read(); p2 = read(); p3 = multi(p1, p2); print(p3); p4 = add(p1, p2); print(p4); return 0; }