逆波兰表达式实现

#include<iostream>
#include<stack>

using namespace std;

//把一个算式先转化为逆波兰表达式

int Priority(char ch)//定义优先级别 
{
	int i;
	switch (ch)
	{
	case'(':i = 1; break;
	case'+':i = 2; break;
	case'-':i = 2; break;
	case'*':i = 4; break;
	case'/':i = 4; break;
	case')':i = 5; break;//优先级最高
	default:i = -1; break;
	}
	return i;
}
void tonibolan(char *ch, char retch[100])
{
	stack<char> st2;
	int i = 0;
	while (*ch != '\0')
	{
		if (*ch >= '0'&&*ch <= '9')
			retch[i++] = *ch;
		else if (*ch == '(')//左括号直接压栈 ,不考虑优先级
			st2.push(*ch);
		else if (*ch == ')')//找到匹配的左括号
		{
			while (st2.top() != '(')
			{
				retch[i++] = st2.top();
				st2.pop();
			}
			st2.pop();
		}
		else if (st2.empty() || Priority(*ch)>Priority(st2.top()))
			st2.push(*ch);
		else
		{
			while (Priority(*ch) <= Priority(st2.top()))
			{
				retch[i++] = st2.top();
				st2.pop();
				if (st2.empty())
					break;
			}
			st2.push(*ch);
		}
		ch++;
	}

	while (!st2.empty())
	{
		retch[i++] = st2.top();
		st2.pop();
	}
	retch[i] = 0;
}

//计算逆波兰表达式的值

int calcval(char *ret)
{

	stack<char> st;
	while (*ret != '\0')
	{
		if (*ret >= '0'&&*ret <= '9')
			st.push(*ret);//数字直接入栈
		else
		{
			switch (*ret)
			{
			case'+':
			{
				char a = st.top();
				st.pop();
				char b = st.top();
				st.pop();
				st.push(((a - '0') + (b - '0') + '0'));//注意类型的运算 
				break;
			}
			case'-':
			{
				char a = st.top();
				st.pop();
				char b = st.top();
				st.pop();
				st.push(((b - '0') - (a - '0')) + '0');
				break;
			}
			case'*':
			{
				char a = st.top();
				st.pop();
				char b = st.top();
				st.pop();
				st.push(((b - '0')*(a - '0')) + '0');
				break;
			}
			case'/':
			{
				char a = st.top();
				st.pop();
				char b = st.top();
				st.pop();
				if (a != '0')
				{
					st.push((((b - '0') / (a - '0')) + '0'));
				}
				else
				{
					cout << "除数为0错误" << endl;
				}
				break;
			}
			}
		}
		ret++;
	}


	return st.top() - '0';
}


int main()
{
	char c;
	int i = 0;
	char ret[100] = {'\0'};
	char ch[100] = {'\0'};
	while (cin >> c)
		ch[i++] = c;
	tonibolan(ch, ret);
	
	i = 0;
	cout << "算式的逆波兰表达式为:" << endl;
	while (ret[i]!='\0')
	{
		cout << ' ' << ret[i++];
	}

	cout << "\n算式的计算结果为:" << endl;
	cout << calcval(ret) << endl;
	
	system("pause");
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值