PAT数据结构练习题——02-线性结构2 一元多项式的乘法与加法运算(C++实现)

1.问题描述

在这里插入图片描述

2.注意事项

在这里插入图片描述

3.代码(C++实现)

#include<iostream>
using namespace std;

typedef struct NODE {
	int xi;
	int zhi;
	struct NODE* next;
}Node;

Node* Get() {
	int num;
	cin >> num;
	Node* node;
	Node* head;
	Node* temp;
	node = new Node;
	node->next = NULL;
	head = node;
	if (num > 0) {
		for (; num > 0; num--) {
			temp = new Node;
			cin >> temp->xi;
			cin >> temp->zhi;
			temp->next = NULL;
			head->next = temp;
			head = head->next;
		}
	}
	return node;
}

void Print(Node* node) {
	Node* p = node->next;
	if (!p) {
		cout << '0' << ' ' << '0' << endl;
	}
	else
		for (; p; p = p->next) {
			if(p->next != NULL)
				cout << p->xi << ' ' << p->zhi << ' ';
			else
				cout << p->xi << ' ' << p->zhi << endl;
		}
}

Node* Add(Node* n1, Node* n2) {
	Node* add = new Node;
	add->next = NULL;
	Node* t1 = n1->next;
	Node* t2 = n2->next;
	Node* head = add;
	Node* temp;
	while (t1 != NULL && t2 != NULL) {
		if (t1->zhi > t2->zhi) {
			temp = new Node;
			temp->next = NULL;
			temp->zhi = t1->zhi;
			temp->xi = t1->xi;
			add->next = temp;
			add = add->next;
			t1 = t1->next;
		}
		else if (t1->zhi < t2->zhi) {
			temp = new Node;
			temp->next = NULL;
			temp->zhi = t2->zhi;
			temp->xi = t2->xi;
			add->next = temp;
			add = add->next;
			t2 = t2->next;
		}
		else if (t1->zhi == t2->zhi) {
			if (t1->xi + t2->xi == 0) {
			}
			else {
				temp = new Node;
				temp->next = NULL;
				temp->zhi = t1->zhi;
				temp->xi = t1->xi + t2->xi;
				add->next = temp;
				add = add->next;
			}
			t1 = t1->next;
			t2 = t2->next;
		}
	}
	if (t2 != NULL)
		add->next = t2;
	else if (t1 != NULL)
		add->next = t1;
	return head;
}

Node* Mul(Node* n1, Node* n2) {
	Node* t1 = n1->next;
	Node* t2 = n2->next;
	Node* mul = new Node;
	mul->next = NULL;
	int i;
	if (t1 == NULL || t2 == NULL) {
		return mul;
	}
	else {
		for (i=1; t1; t1 = t1->next,i++) {
			Node* hang = new Node;
			hang->next = NULL;
			Node* headhang = hang;
			for (t2 = n2->next; t2; t2 = t2->next) {
				Node* temp = new Node;
				temp->next = NULL;
				temp->xi = t1->xi * t2->xi;
				temp->zhi = t1->zhi + t2->zhi;
				hang->next = temp;
				hang = hang->next;
			}
			mul = Add(mul, headhang);
		}
		return mul;
	}
}

int main() {

	Node* n1;
	n1 = Get();
	Node* n2;
	n2 = Get();
	Node* mul;
	mul = Mul(n1, n2);
	Print(mul);
	Node* add;
	add = Add(n1, n2);
	Print(add);

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值