您的位置:首页 > 理论基础 > 数据结构算法

02-线性结构2 一元多项式的乘法与加法运算

2016-09-24 22:46 447 查看
设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 数据结构 链表