【C++】顺序栈实现后缀表达式计算

题目:

使用栈实现后缀表达式计算

要求:

使用栈实现后缀表达式计算,其中,在后缀表达式中,输入的数字为整数,且为正数,数字、符号之间用逗号隔开,整个后缀表达式用“#”表示结束。

输入样例:

11 2 3 + *#

输出样例:

55

//顺序栈实现后缀表达式计算
//author:Mitchell
//data:3.16
#include<iostream>
using namespace std;
class stack
{
private:
	double* st;
	int size;
	int top;
public:
	stack(int sizevalue)
	{
		size = sizevalue;
		top = -1;
		st = new double[size];
	}
	stack()
	{
		size = 10;
		top = -1;
		st = new double[size];
	}
	~stack()
	{
		delete[] st;
		top = -1;
	}
	bool isEmpty();
	bool push(const double pushvalue);
	bool pop(double& popvalue);
};
bool stack::isEmpty()
{
	if (top == -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool stack::push(const double pushvalue)
{
	if (top == size)
	{
		cout << "stack has been already full, can't push" << endl;
		return false;
	}
	st[++top] = pushvalue;
	return true;
}
bool stack::pop(double& popvalue)
{
	if (top == -1)
	{
		cout << "stack is empty, can't pop" << endl;
		return false;
	}
	popvalue = st[top--];
	return true;
}

class calculator
{
private:
	stack data;
public:
	void run();
	void calculate(char o);
	void clear();
	bool get(double& a, double& b);
};
void calculator::run()
{
	char instream;
	double number;
	while (cin >> instream)
	{
		if (instream == '#')
		{
			break;
		}
		switch (instream)
		{
		case'+':
		case'-':
		case'*':
		case'/':
			calculate(instream);
			break;
		default:
			cin.putback(instream);
			cin >> number;
			data.push(number);
		}
	}
	double finalnumber;
	if (data.pop(finalnumber))
	{
		cout << finalnumber << endl;
	}
}
void calculator::calculate(char symbolvalue)
{
	double a, b;
	if (get(a, b))
	{
		switch (symbolvalue)
		{
		case'+':
		{
			data.push(a + b);
			break;
		}
		case'-':
		{
			data.push(a - b);
			break;
		}
		case'*':
		{
			data.push(a * b);
			break;
		}
		case'/':
		{
			if (b == 0.0)
			{
				clear();
				break;
			}
			else
			{
				data.push(a / b);
				break;
			}
		}
		}
	}
	else
	{
		clear();
	}
}
void calculator::clear()
{
	data.~stack();
}
bool calculator::get(double& a, double& b)
{
	if (data.isEmpty())
	{
		return false;
	}
	data.pop(a);
	if (data.isEmpty())
	{
		return false;
	}
	data.pop(b);
	return true;
}
int main()
{
	calculator test;
	test.run();
}

猜你喜欢

转载自blog.csdn.net/Mitchell_Donovan/article/details/114851838