(计蒜客)利用栈实现表达式转换并求得结果

#include 
#include 
#include 
using namespace std;

template
class Stack {
private:
	Type* elements;
	int max_size, top_index;   //分别表示容量和顶部元素
public:
	Stack(int input_size) {
		elements = new Type[max_size];
		max_size = input_size;
		top_index = -1;   //从零开始计算,所以设为-1
	}
	
	bool mypush(Type element);  //插入元素
	bool mypop();  //弹出首元素
	bool myempty();  //判断是否为空
	Type mytop();   //返回栈顶元素
};

template
Type Stack::mytop()
{
	assert(top_index >= 0);
	return elements[top_index];
}

template
bool Stack::myempty()
{
	return top_index < 0;
}

template
bool Stack::mypop()
{
	if (top_index < 0) {
		return false;
	}

	top_index--;
	return true;
}

template
bool Stack::mypush(Type element)
{
	if (top_index + 1 >= max_size) {
		return false;
	}

	top_index++;
	elements[top_index] = element;
	return true;
}

//判断表达式优先级
int precede(char a) {
	switch (a)
	{
	case '+':
		return 1;
	case '-':
		return 1;
	case '*':
		return 2;
	case '/':
		return 2;
	default:
		return 0;
	}
}

//比较优先级
bool comparePrecede(char a, char b) {  
	
	int preA = precede(a);
	int preB = precede(b);

	if (preA >= preB)
		return true;
	else
		return false;
}

//比较优先级列表
float operate(char theta, float a, float b) {  
	switch (theta)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a * b;
	case '/':
		return a / b;
	default:
		return 0;
	}
}

//计算值
void calc(Stack& numbers, Stack& operators) {
    
	float a = numbers.mytop();
	numbers.mypop();
	float b = numbers.mytop();
	numbers.mypop();
	
	numbers.mypush(operate(operators.mytop(),b,a));
	operators.mypop();
}

//计算具体值
int main() {

	int n = 0;  //栈的结构大小
	cin >> n;  
	Stack numbers(n);  //用来存储数据
	Stack operators(n);  //用来存储运算符
	string buffer;    //输入的表达式
	cin >> buffer;
	int i = 0;
	while (i < n) {
		if (isdigit(buffer[i])) {
			numbers.mypush((float)(buffer[i] - '0'));
			i++;
		}
		else {
			//比较优先级
			if (operators.myempty() || comparePrecede(buffer[i], operators.mytop())) {
				operators.mypush(buffer[i]);
				i++;
			}
			else {
				calc(numbers, operators);  //进行一次运算
			}
		}
	}
	
	cout << numbers.mytop() << endl;

	system("PAUSE");
	return 0;
}

 

你可能感兴趣的:(ACM算法习题)