栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

按照王道书上的算法

#include
#include
#include
using namespace std;
class Test
{
private:
	string str;
	stack 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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982486.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号