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

代码以及解析


#include 
#include 
#include 
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 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;
}

你可能感兴趣的:(C++,算法)