
设计函数分别求两个一元多项式的乘积与和。
输入格式:输入分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
我是笨比,我能找一年的bug还找不出来呜呜呜,我要把它刻进我的DNA 中,我恨。
代码:#includeusing namespace std; typedef struct li { int co; //系数 int in; //指数 struct li* next; }*List; List read(List p); void ad(List p1, List p2); void mu(List p1, List p2); static int f = 0; int main() { List p1 = NULL, p2 = NULL, add = NULL, mul = NULL; p1=read(p1); p2=read(p2); if (f<2) { mu(p1, p2); cout << "n"; ad(p1, p2); } else cout << "0 0"; return 0; } List read(List p) { int n, c, i; cin >> n; if (n <= 0) f += 1; p = (List)malloc(sizeof(struct li)); List head = p, t = NULL; for (int j = 0; j < n; j++) { t = (List)malloc(sizeof(struct li)); cin >> c >> i; t->co = c; t->in = i; p->next = t; p = t; } p->next = NULL; return head; } void ad(List p1, List p2) { List a, h = NULL, t; a = (List)malloc(sizeof(struct li)); h = a; while (p1->next && p2->next) //为啥是next呢,因为我们前面读入的链表头头指向的是一个空结点,所以要从next项开始 { t = (List)malloc(sizeof(struct li)); if (p1->next->in > p2->next->in) //两两指数对比,大的那个项存起来再将所处链表往后移动 { t->co = p1->next->co; t->in = p1->next->in; a->next = t; a = t; p1 = p1->next; } else if (p1->next->in < p2->next->in) { t->co = p2->next->co; t->in = p2->next->in; a->next = t; a = t; p2 = p2->next; } else //指数相等时即可相加 { t->co = p1->next->co + p2->next->co; t->in = p1->next->in; a->next = t; a = t; p1 = p1->next; p2 = p2->next; } } if (p1->next) a->next = p1->next; else a->next = p2->next; while (h->next) { if (h->next->co != 0) { cout << h->next->co << " " << h->next->in; h = h->next; if (h->next) cout << " "; } } } void mu(List p1, List p2) { List h = NULL, m = NULL, t = NULL; m = (List)malloc(sizeof(struct li)); h = m; List p = p1->next; while (p) { t = (List)malloc(sizeof(struct li)); t->co = p2->next->co * p->co; t->in = p2->next->in + p->in; m->next = t; m = t; p = p->next; } m->next = NULL; p2 = p2->next; while (p2->next) { p = p1->next; while (p) { t = (List)malloc(sizeof(struct li)); t->co = p2->next->co * p->co; t->in = p2->next->in + p->in; m = h; while (m->next) { if (t->in > m->next->in) { List temp = m->next; m->next = t; t->next = temp; break; } else if(t->in == m->next->in) { m->next->co += t->co; break; } m = m->next; } if (m->next == NULL) { m->next = t; t->next = NULL; } p = p->next; } p2 = p2->next; } while (h->next) { if (h->next->co != 0) { cout << h->next->co << " " << h->next->in; h = h->next; if (h->next) cout << " "; } } }
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)