【学习】C++中缀表达式转后缀表达式(逆波兰式)【有代码】

方法一:括号法(直接获得结果)

1、在运算符的两边加上括号

2、把符号移动到符号所在括号后边

3、去除所有括号

例:8*(3-1)—2/5

1、((8*(3-1))-(2/5))

2、((8(31)-)*(25)/)-

3、8 3 1 - * 2 5 / -

 【2分钟秒杀-中缀表达式转前后缀表达式】 https://www.bilibili.com/video/BV1aV4y1771G/?share_source=copy_web&vd_source=d04bc972ba0b1aff78f14b3cdc972a6c

 方法二:栈的应用

例:8*(3-1)-2/5

步骤(遍历字符串后进行判断)

1、数字直接加入逆波兰字符串 

 

 2、获得运算符时,判断栈不为空 且优先级不小于栈顶元素,就出栈,否则入栈

 

此时栈顶元素优先级高于当前元素,因此先出栈再入栈

3、左括号直接加入符号字符串

4、遇到右括号时,判断栈不为空并且栈顶不是(时,把符号放入逆波兰容器,同时出栈,遇到(,再把(出栈 

 5、当所有的中序表达式遍历完后,在栈内的符号依次出栈

 

6、拼接结果字符串

函数代码

#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
//中缀表达式 3 + 2 * 2
//后缀表达式 3 2 2 * +
bool isOperator(char ch) {
	return ch == '+' || ch == '-' || ch == '*'|| ch == '/';
}
int precedence(char op) {
	if (op == '+' || op == '-')return 1;
	if (op == '*' || op == '/')return 2;
	return 0;
	
}

//将中缀表达式转换为逆波兰表达式
/*
1、数字直接加入逆波兰字符串
2、左括号直接加入符号字符串
3、遇到右括号时,判断栈不为空并且栈顶不是(时,把符号放入逆波兰容器,同时出栈,遇到(,再把(出栈
4、获得运算符时,判断栈不为空 且优先级不小于栈顶元素,就出栈,否则入栈
5、当所有的中序表达式遍历完后,在栈内的符号依次出栈
6、拼接结果字符串
*/
string infixToPostfix(const string& infix) {
	stack<char>ops;
	vector<char> postfix;

	for (char ch : infix) 
	{
		if (isspace(ch))continue;
		if (isdigit(ch))
		{
			postfix.push_back(ch);
		}
		else if (ch =='(')
		{
			ops.push(ch);
		}
		else if (ch==')')
		{
			while (!ops.empty() && ops.top()!='(')
			{
				postfix.push_back(ops.top());
				ops.pop();
			}
			//弹出‘(’
			if (!ops.empty())
			{
				ops.pop();
			}
		}
		else if (isOperator(ch))
		{
			while (!ops.empty() && precedence(ops.top()) >= precedence(ch))
			{
				postfix.push_back(ops.top());
				ops.pop();
			}
			//栈为空或者优先级底就直接加入
			ops.push(ch);
		}
	}

	while (!ops.empty())
	{
		postfix.push_back(ops.top());
		ops.pop();
	}
	string result;
	for (char ch : postfix) {
		result += ch;
	}
	return result;
}
int main() {
	string infix = "8*(3-1)-2/5";
	string postfix = infixToPostfix(infix);
	cout << "Postfix expreesion:" << postfix << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值