【C++】单链表实现多项式加法运算

题目:

请使用单链表实现两个多项式的加法运算,其中多项式的项按指数从高到低排列。例如3x^2-x+2输入形式为3  2  -1  1  2  0

 

测试样例:

样例1:

输入样例:

3  4  2  3  1  2(第一个多项式)

-2  3  4  2  5  1  6  0(第二个多项式)

输出样例:

3  4  5  2  5  1  6  0求和结果)

样例2:

输入样例:

3  10000  2  1

2  100  -2  1  1  0

输出样例:

3  10000  2  100  1  0

//单链表实现多项式加法
//author:Mitchell_Donovan
//date:2021.3.9
#include<iostream>
using namespace std;

template<class T>
class link
{
public:
	T number, index;
	link<T>* next;
	link(const T numberValue, const T indexValue)
	{
		number = numberValue;
		index = indexValue;
		next = NULL;
	}
};

template <class T>
class linkList {
private:
	link<T>* head = new link<T>(0, 0);
public:
	linkList() {
		head->next = NULL;
	}
	~linkList() {
		link<T>* p;
		while (head != NULL) {
			p = head;
			head = head->next;
			delete p;
		}
	}
	bool print();
	bool insert(const T numberValue, const T indexValue);
	bool add(linkList<T> a, linkList<T> b);
};

template<class T>
bool linkList<T>::print() {
	link<T>* p = head->next;
	cout << "f(x)= ";
	if (p == NULL) {
		cout << "0" << endl;
		return false;
	}
	while (p != NULL) {
		if (p->number != 0) {
			cout << p->number << "x^" << p->index;
			break;
		}
		p = p->next;
	}
	p = p->next;
	while (p != NULL) {
		if (p->number != 0) {
		cout << " + " << p->number << "x^" << p->index;
		}
		p = p->next;
	}
	cout << endl;
	return true;
}

template<class T>
bool linkList<T>::insert(const T numberValue, const T indexValue)
{
	link<T>* p = head;
	link<T>* q = new link<T>(numberValue, indexValue);
	q->next = p->next;
	p->next = q;
	return true;
}

template<class T>
bool linkList<T>::add(linkList<T> a, linkList<T> b) {
	link<T>* p = a.head->next,* q = b.head->next;
	while (p != NULL && q != NULL) {
		if (p->index < q->index) {
			insert(p->number, p->index);
			p = p->next;
		}
		else if (p->index > q->index) {
			insert(q->number, q->index);
			q = q->next;
		}
		else if (p->index == q->index) {
			insert(p->number + q->number, p->index);
			p = p->next;
			q = q->next;
		}
	}
	while (p != NULL) {
		insert(p->number, p->index);
		p = p->next;
	}
	while (q != NULL) {
		insert(q->number, q->index);
		q = q->next;
	}
	return true;
}



int main() {
	linkList<int> La, Lb, Lc;
	int size;
	int number, index;
	cout << "请输入第一个多项式的项数:" << endl;
	cin >> size;
	cout << "请输入各项和其指数:" << endl;
	for (int i = 1; i <= size; i++) {
		cin >> number >> index;
		La.insert(number, index);
	}
	La.print();
	cout << "请输入第二个多项式的项数:" << endl;
	cin >> size;
	cout << "请输入各项和其指数:" << endl;
	for (int i = 1; i <= size; i++) {
		cin >> number >> index;
		Lb.insert(number, index);
	}
	Lb.print();
	Lc.add(La, Lb);
	Lc.print();
}

 

猜你喜欢

转载自blog.csdn.net/Mitchell_Donovan/article/details/114808315
今日推荐