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

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值