中序表达式转后缀表达式

中缀表达式X=A+B*(C-(D+F))/E转后缀表达式之后是什么?
ABCDF+-*E/+
ABDF+C-*E/+
ABDF+C*-E/+

ABDF+C*-E+/

中缀表达式转后缀表达式的方法:
1.遇到操作数:直接输出(添加到后缀表达式中)
2.栈为空时,遇到运算符,直接入栈
3.遇到左括号:将其入栈
4.遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出。
5.遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈
6.最终将栈中的元素依次出栈,输出。

#include<iostream>
#include<string>
#include<stdlib.h>
#include<stack>
#include<map>
#include<vector>
using namespace std;
int type(char ch)
{
	if (ch >= 'A'&&ch <= 'Z')return 1;
	if (ch == '+' || ch == '-' || ch == '*' || ch == '/')return 0;
	return -1;
}
int main()
{
	string str = "A+B*(C-(D+F))/E";
	map<char, int>priority;
	stack<char>st;
	string s;
	priority.insert(make_pair('+', 0));
	priority.insert(make_pair('-', 0));
	priority.insert(make_pair('*', 1));
	priority.insert(make_pair('/', 1));
	priority.insert(make_pair('(', 2));
	int i = 0;
	while (i < str.length())
	{
		if (type(str[i]) == 1)s = s + str[i];
		else if (type(str[i]) == 0)
		{
			if (st.empty())//还没有字符
			{
				st.push(str[i]);
			}
			else
			{
				while (1)
				{
					char ch = st.top();
					if (ch == '(')
					{
						break;
					}
					if (priority[ch] >= priority[str[i]])//比将其优先级高的符号输出
					{
						s = s + ch;
						st.pop();
					}
					else
					{
						break;
					}
					if (st.empty())break;
				}
				st.push(str[i]);
			}
		}
		else if (type(str[i]) == -1)
		{
			if (str[i] == '(')st.push(str[i]);
			else
			{
				while (1)
				{
					char ch = st.top();
					if (ch != '(')
					{
						s = s + ch;
						st.pop();
					}
					if (ch == '(')//找到配对的
					{
						st.pop();
						break;
					}
					if (st.empty())break;
				}
			}
		}
		i++;
	}
	while (!st.empty())
	{
		s = s + st.top();
		st.pop();
	}
	cout << s << endl;
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值