中缀表达式转换为后缀表达式

代码以及解析


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

// '+' '-' '*' '/'
int prase(char c)
{
	if (c == '*' || c == '/')
		return 2;
	else if (c == '+' || c == '-')
		return 1;
	else
		return 0;
}

void Func(string& post, string& target)
{
	string final_string;
	stack<char> st;
	for (auto& ch : post)
	{
		// 判断是是否为字母或者数字
		if (isalpha(ch)||isdigit(ch))
		{
			final_string += ch;
		}
		// 如果是左括号直接入栈
		else if (ch == '(')
		{
			st.push(ch);
		}
		// 如果是右括号那么开始出栈栈中的元素
		// 直到出栈到左括号为止
		else if (ch == ')')
		{
			while (!st.empty() && st.top() != '(')
			{
				final_string += st.top();
				st.pop();
			}
			if (!st.empty() && st.top() == '(')
			{
				st.pop();
			}
		}
		// 如果是运算符
		// 判断他们的优先级
		// 如果当前所遍历的运算符优先级小于等于当前栈顶的运算符的优先级
		// 那么就出栈栈中的元素,直到该条件不成立为止(当然栈此时不能为空)
		else
		{
			while (!st.empty() && prase(ch) <= prase(st.top()))
			{
				final_string += st.top();
				st.pop();
			}
			st.push(ch);
		}

	}
	// 当我们遍历完毕之后,如果栈中还有元素,直接打印即可
	while (!st.empty())
	{
		final_string += st.top();
		st.pop();
	}
	target = final_string;
}
int main()
{
	string post("a+b*(c+d)/e");
	string target;
	// 我们使用回调函数来对post进行中缀表达式转换为后缀表达式
	Func(post, target);
	cout << target << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁百万

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值