5-2 一元多项式的乘法与加法运算 (20分) (单向链表)

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

输入格式:

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

/*  数最大才不超过10000的 毫无MLE风险 差点就偷懒用数组存储写了 QvQ..*/
#include "iostream"
#include "string"
using namespace std;
struct Node {
	int coef;
	int exp;
	Node* next;
};
typedef Node* List;

/*
 * 尾插法
*/
List Attach(List rear, int coef,int exp) {  
	List p = (List)malloc(sizeof(Node));
	p->coef = coef;
	p->exp =  exp;
	p->next = NULL;
	rear->next = p;
	rear = rear->next;
	return rear;
}

/* 多项式相加
 */
List AddPoly(List l1,List l2) {
	List  p = (List)malloc(sizeof(Node));
	p->next = NULL;
	List rear = p;
	while (l1 != NULL && l2!= NULL) {
		if (l1->exp > l2->exp) {
			rear = Attach(rear, l1->coef,l1->exp);
			l1 = l1->next;
		}
		else if (l2->exp > l1->exp) {
			rear = Attach(rear,l2->coef,l2->exp);
			l2 = l2->next;
		}
		else {
			if (l1->coef + l2->coef != 0)
				rear = Attach(rear, l1->coef + l2->coef, l1->exp);
			l1 = l1->next; l2 = l2->next;
		}
	}
	while (l1 != NULL) {
		rear = Attach(rear, l1->coef, l1->exp);
		l1 = l1->next;
	}
	while (l2 != NULL) {
		rear = Attach(rear, l2->coef, l2->exp);
		l2 = l2->next;
	}
	return p->next;
}

List Multiply(List l1,List l2) {  //多项式相乘
	List p = (List)malloc(sizeof(Node));
	p->next = NULL;
	List s = l2;
	List k = NULL;  
	List rear = p;
	while (l1 != NULL) {
		l2 = s;
		rear = p;
		while (l2 != NULL) {
			rear = Attach(rear,l1->coef*l2->coef,l1->exp+l2->exp);
			l2 = l2->next;
		}
		k = AddPoly(k,p->next);
		l1 = l1->next;
	}
	return k;
}
List ReadPoly() { //读入多项式
	List p = (List)malloc(sizeof(Node));
	List rear = p;
	p->next = NULL;
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		int exp, coef;
		cin >> coef >> exp;
		rear = Attach(rear,coef,exp);
	}
	return p->next;
}

void Print(List l) { //打印多项式
	int k = 0;
	if (l == NULL) {
		cout << "0 0";
	}
	else {
		while (l != NULL) {
			if (k == 0) {
				cout << l->coef << " " << l->exp;
				k = 1;
			}
			else {
				cout << " " << l->coef << " " << l->exp;
			}
			l = l->next;
		}
	}
	cout << endl;
}
int main() {
	List l1, l2;
	List p;
	l1 = ReadPoly();
	l2 = ReadPoly();
	p = Multiply(l1, l2);
	Print(p);
	p = AddPoly(l1,l2);
	Print(p);
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值