0
点赞
收藏
分享

微信扫一扫

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


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

所谓中缀表达式,指的是运算符处于操作数的中间(例:3 * ( 4 + 2 )),中缀表达式是人们常用的算术表示方法,但中缀表达式不容易被计算机解析,因为既要考虑运算符的优先级,还要考虑括号的处理。但中缀表达式仍被许多程序语言使用,因为它符合人们的普遍用法。后缀表达式,指的是不包含括号,运算符放在两个操作数的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,也不需要考虑括号)。

给出一个中缀表达式,请将其转换为后缀表达式并输出。

输入格式:
只有一行,是一个长度不超过1000的字符串,表示一个中缀表达式。表达式里只包含±*/与小括号这几种符号。其中小括号可以嵌套使用。运算符、操作数之间用一个空格分隔,数据保证输入的操作数中不会出现负数,保证除数不会为0。

输出格式:
输出对应的后缀表达式。运算符、操作数之间用一个空格分隔,但行尾无多余空格。

输入样例:
3 * ( 4 + 2 )
输出样例:
3 4 2 + *

入栈出栈…
是数字直接输出,考虑到有的数字会不是个位数需要想办法计算完之后再输出
是运算符就查看栈顶元素,如果栈顶元素运算符优先级大于等于目前读入的运算符优先级,就弹出栈顶运算符,直到小于或者栈空为止
如果是左括号直接入栈
如果是右括号,弹出栈里的元素直到遇见左括号.

#include<iostream>
#include<stack>
#define print {if(flag==1)cout<<' ';else flag=1;}
using namespace std;
int lev(char ch) {
	if(ch=='+'||ch=='-')return 0;
	else if(ch=='*'||ch=='/')return 1;
	else if(ch=='(')return 100;
	abort();
}
int flag;
int main() {
	int t=0;
	int flag2=0;
	char ch;
	string str="+-*/";
	stack<char> st;
	// freopen("7-3 中缀表达式转换为后缀表达式.txt","r",stdin);
	while((ch=getchar())!=EOF) {
		if(ch==' '){
			if(flag2==1){
				print cout<<t;
				t=0;
				flag2=0;
			}
			continue;
		}
		if(str.find(ch)!=string::npos) {
			if(st.empty()||lev(ch)>lev(st.top())) {
				st.push(ch);
			} else if(lev(ch)<=lev(st.top())) {
				while(!st.empty()&&lev(ch)<=lev(st.top())&&st.top()!='(') {
					print cout<<st.top();
					st.pop();
				}
				st.push(ch);
			}
		} else if(ch==')') {
			while(st.top()!='(') {
				print cout<<st.top();
				st.pop();
			}
			st.pop();
			continue;
		} else if(ch=='(') {
			st.push('(');
		} else {
			t=t*10+ch-'0';
			flag2=1;
		}
	}
	if(flag2==1){
		print cout<<t;
	} 
	while(!st.empty()) {
		print cout<<st.top();
		st.pop();
	}
}


举报

相关推荐

0 条评论