设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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<iostream> #include<cstdio> using namespace std; struct ListNode { int coef; int expo; ListNode *next; }; class LinkList { private: int len; ListNode *head; public: LinkList() { head = new ListNode(); head->next = NULL; len = 0; } //依次插入到链表末端 void insert(int _coef, int _expo) { if (_coef == 0) return; ListNode *s = head; while (s->next) s = s->next; ListNode *p = new ListNode(); p->coef = _coef; p->expo = _expo; p->next = NULL; s->next = p; len++; } void add(LinkList &a, LinkList &b) { ListNode *p = a.head, *q = b.head; //依次比较链表a和链表b的每一个结点,直到至少有一个结点为空 while (p->next&&q->next) { if (p->next->expo == q->next->expo) { insert(p->next->coef + q->next->coef, p->next->expo); p = p->next; q = q->next; } else if (p->next->expo > q->next->expo) { insert(p->next->coef, p->next->expo); p = p->next; } else { insert(q->next->coef, q->next->expo); q = q->next; } } //将a链表之后的结点依次插入 while (p->next) { insert(p->next->coef, p->next->expo); p = p->next; } //将b链表之后的结点依次插入 while (q->next) { insert(q->next->coef, q->next->expo); q = q->next; } } void display() { if (len == 0) cout << "0 0" << endl; else { ListNode *p = head->next; cout << p->coef << " " << p->expo; while (p->next) { p = p->next; cout << " " << p->coef << " " << p->expo; } cout << endl; } } LinkList mult(LinkList &a, LinkList &b) { ListNode *p = a.head, *q = b.head; if (!p->next || !q->next) return *this; while (p->next) { p = p->next; LinkList result; //result用于存放每一步链表相加的结果 LinkList temp; q = b.head; while (q->next) { q = q->next; temp.insert(q->coef*p->coef, q->expo + p->expo); } result.add(*this,temp); *this = result; } return *this; } }; int main() { int n; cin >> n; LinkList A; int coef, expo; for (int i = 0; i < n; i++) { cin >> coef >> expo; A.insert(coef, expo); } cin >> n; LinkList B; for (int i = 0; i < n; i++) { cin >> coef >> expo; B.insert(coef, expo); } LinkList C; C=C.mult(A, B); C.display(); LinkList D; D.add(A,B); D.display(); return 0; }