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

#include <iostream>
#include <string>
#include <cassert>
using namespace std;

template<typename Type>
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<typename Type>
Type Stack<Type>::mytop()
{
	assert(top_index >= 0);
	return elements[top_index];
}

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

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

	top_index--;
	return true;
}

template<typename Type>
bool Stack<Type>::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<float>& numbers, Stack<char>& 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<float> numbers(n);  //用来存储数据
	Stack<char> 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值