数据结构_链表_稀疏多项式求值_C++实现

数据结构_链表_稀疏多项式求值_C++实现

“head.h”

#include<iostream>
#include<cmath>
using namespace std;

class PolyTerm
{
public:
	PolyTerm();
	int coef;
	int exp;
	PolyTerm *next;
};

PolyTerm::PolyTerm()
{
	coef = exp = 0;
	next = NULL;
}

class DATA
{
public:
	DATA();
	void GetPoly();
	void GetX();
	void GetSum();
private:
	int GetPow(int, int);
	PolyTerm *head, *p;
	int result, x;
};

DATA::DATA()
{
	head = p = NULL;
	x = result = 0;
}

void DATA::GetPoly()
{
	cout << "Please Input Data :" << endl << endl;
	int coef, exp;
	bool first = true;
	while (cin >> coef >> exp)
	{
		if (first)
		{
			head = new PolyTerm;
			head->coef = coef;
			head->exp = exp;
			p = head;
			first = !first;
		}
		else
		{
			p->next = new PolyTerm;
			p = p->next;
			p->coef = coef;
			p->exp = exp;
		}
	}
	cin.clear(); //解除cin的异常状态
}

void DATA::GetX()
{
	cout << "GetX Called !" << endl << endl;
	if (head == NULL)
	{
		cout << "No Data Input !" << endl << endl;
		return;
	}
	cout << "Please Input X :" << endl << endl;
	cin >> x;
}

void DATA::GetSum()
{
	cout << "GetSum Called !" << endl << endl;
	if (head == NULL)
		cout << "sum = 0" << endl << endl;
	else
	{
		result = (head->coef) * GetPow(x, head->exp);
		p = head->next;
		while (p != NULL)
		{
			result += p->coef * GetPow(x, p->exp);
			p = p->next;
		}
		cout << "sum = " << result << endl << endl;
	}
}

int DATA::GetPow(int x, int e)
{
	return int(pow(double(x), double(e)));
}
"main.cpp"
#include"head.h"
#include<iostream>
using namespace std;
 
int main()
{
	DATA data;
	data.GetPoly();
	data.GetX();
	data.GetSum();
	system("pause");
	return 0;
}

发表回复