问题 B: 数据结构作业01 -- 一元多项式的求和
时间限制: 1 Sec 内存限制: 128 MB提交: 2336 解决: 456
[提交][状态][讨论版]
题目描述
一个一元多项式可以看作由若干个一元单项式按降幂排列成的线性表。请编写程序对输入的两个一元多项式求和,并输出求和的结果。
输入
输入为两个一元多项式,每个一元多项式输入一行,按照降幂依次输入每个单项式的系数和指数,并以-1 -1作为结束。系数和指数均为整数,指数不小于0。
输出
输出为求和结果多项式,按照降幂依次输出每个单项的系数和指数,每个数值后面用一个空格隔开,输出结果多项式后换行。 系数为0的单项式不得输出——除非结果多项式就是0,则直接输出0。
样例输入
2 7 3 5 12 1 6 0 -1 -1
7 5 9 4 3 0 -1 -1
样例输出
2 7 10 5 9 4 12 1 9 0
#include "iostream" #include "algorithm" #include "cstdio" #include "cstring" using namespace std; struct Point { int a; int b; Point *next; }; Point *creat() { Point *h,*s,*t; h = new(Point); s = h; h = new(Point); s->next = h; t = NULL; cin >> h->a >> h->b; while(h->a != -1 &&h->b != -1) { t = h; h = new(Point); cin >> h->a >> h->b; t->next = h; } h->next = NULL; return s; } Point *add(Point *h1,Point *h2) { Point *p, *q, *pre, *temp; p = h1->next; q = h2->next; pre = h1; int sum; while (p != NULL && q != NULL) { //此处bug if (p->b > q->b) { pre->next = p; pre = pre->next; p = p->next; } else if (p->b < q->b) { pre->next = q; pre = pre->next; q = q->next; } else { sum = p->a + q->a; if (sum != 0) { p->a = sum; pre->next = p; pre = pre->next; p = p->next; temp = q; q = q->next; free(temp); } else { temp = p->next; free(p); p = temp; temp = q->next; free(q); q = temp; } } if (p != NULL) { //此处bug pre->next = p; } else { pre->next = q; } } return h1; } int main() { Point *h1,*h2,*h; h1 = creat(); h2 = creat(); h = add(h1,h2); if(h->next->b == -1) //此处bug cout << "0 "<<endl; else { for(Point *t = h->next;t->b != -1;t = t->next) { cout << t->a << " " << t->b << " "; } cout << endl; } return 0; }
这指针搞得我要精神分裂了!!!!!!!!!!!
改bug改了一天,终于AC了
11/1号更新:当测试时出现无限循环的大数字的时候是for中出现指针超过判断条件了p->next !=NULL 被直接跳过了结果p->next一直运行下去输出有规律的大数