C++中缀表达式转后缀表达式

按照王道书上的算法

在这里插入图片描述

#include<iostream>
#include<string>
#include<stack>
using namespace std;
class Test
{
private:
	string str;
	stack<char> st;
public:
	Test(string str);
	string Postfix();
};
int main()
{
	while (1) {
		string str;
		cin >> str;
		Test A(str);
		cout << A.Postfix() << endl;

	}
	return 0;
}
Test::Test(string str)
{
	this->str = str;
}
string Test::Postfix()
{
	char ch;
	char old_ch;
	string str1;
	for (int i = 0; i < str.length(); i++)
	{
		ch = str[i];
		//如果是数字  直接加到字符串中
		if (ch <= '9' && ch >= '0') {
			str1 += ch;
			
		}
		//左括号入栈
		if (ch == '(')
		{
			st.push(ch);
		}
		//右括号循环出栈,直到遇到左括号
		if (ch == ')')
		{
			while (st.top() != '(')
			{
				old_ch = st.top();
				str1 += old_ch;
				st.pop();
			}
			st.pop();
		}
		//加减乘除情况
		if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
		{
			str1 += '#';//分割数字
			//加减为最低优先级,直接出栈就可以
			if (ch == '+' || ch == '-') {
				while (!st.empty()){
					old_ch = st.top();
					if (old_ch == '(')
					{
						break;
					}
					st.pop();
					str1 += old_ch;

				}
				st.push(ch);
			}
			//乘除
			else {
				while (!st.empty())
				{
					old_ch = st.top();
					if (old_ch == '(')
					{

						break;
					}
					//乘除只有遇到乘除才可以直接出栈
					if (old_ch == '*' || old_ch == '/') {
						st.pop();
						str1 += old_ch;
					}
					else {
						break;
					}

				}
				st.push(ch);
			}



		}
	}
	while (!st.empty())
	{
		str1 += st.top();
		st.pop();
	}
	return str1;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值