中缀表达式转后缀表达式

一个非常简单的中缀表达式转后缀表达式

输入:

一个中缀算术表达式,操作数限定为0~9,运算法则限定为+、-、*、/。

输出:

一个后缀(逆波兰式)算术表达式

例子:

  • 输入:1+(9-3)*3
  • 输出:1 9 3 - 3 * +
#include<iostream>
#include<stack>
#include<queue>
#include<string>
using namespace std;

//优先级比较函数
int bgthan(char ch1, char ch2) {
	//从左到右,一次是+,-,*,/的优先级,数字越大越高
	char op[5] = { '+','-','*','/','('};
	
	int a[][5] = {
		{0,0,0,0,0},
		{0,0,0,0,0},
		{1,1,1,1,0},
		{1,1,1,1,0},
		{0,0,0,0,0}
	};
	
	int i, j;
	for (i = 0; i < 5; i++) {
		if (ch1 == op[i])break;
	}
	for (j = 0; j < 5; j++) {
		if (ch2 == op[j])break;
	}
	return a[i][j];
}

//中缀转后缀表达式
string pre2post(string pre) {
	int n = pre.length();  //表达式的长度
	stack<char> opter;  //操作符栈
	string post = "";
	for (int i = 0; i < n; i++) {
		if (pre[i] >= '0'&&pre[i] <= '9') {  //数字直接输出
			post += pre[i];  //添加到末尾
			post += ' ';  //添加空格分割
		}
		else {  //操作符
			//左括号或者栈空直接入栈
			if (pre[i] == '('||opter.empty()) {
				opter.push(pre[i]);
			}
			//如果是右括号
			else if (pre[i] == ')') {
				//出栈直到遇到'(’
				while (opter.top() != '(') {
					post += opter.top();
					post += ' ';
					opter.pop();
				}
				opter.pop();  //弹出'('
				if (opter.empty()) {
					cout << "栈已空" << endl;
				}
			}
			//运算符则比较优先级
			else 
			{
				//栈顶元素优先的话
				if (bgthan(opter.top(), pre[i])) {
					post += opter.top();
					opter.pop();  //出栈
					post += ' ';
					
				}
				//入栈
				opter.push(pre[i]);
			}
		}
	}
	while (!opter.empty()) {
		post += opter.top();
		opter.pop();
	}
	
	return post;
}


int main() {
	string str;
	cin >> str;
	cout << pre2post(str) << endl;
	system("pause");
}

原文地址:https://www.cnblogs.com/urahyou/p/12653142.html