中缀表达式转后缀表达式(c++)

  1. 初始化两个栈:运算符栈s1和储存中间结果的栈s2;
  2. 从左至右扫描中缀表达式;
  3. 遇到操做数时,将其压s2;
  4. 遇到运算符时,比较其与s1栈顶运算符的优先级:
    1. 若是s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
    2. 不然,若优先级比栈顶运算符的高,也将运算符压入s1
    3. 不然,将s1栈顶的运算符弹出并压入到s2中,再次转到(4-1)与s1中新的栈顶运算符相比较;
  5. 遇到括号时:
    1. 若是是左括号“(”,则直接压入s1;
    2. 若是是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃;
  6. 重复步骤2至5,直到表达式的最右边;
  7. 将s1中剩余的运算符依次弹出并压入s2;
  8. 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式

代码:ios

#include<iostream>
#include<cstring>
#include<algorithm> 
#include<stack>
using namespace std;

stack<char> s1;		//运算符栈 
stack<char> s2;		//中间结果栈 

int f(const char str){
	int yxj;		//优先级 
	switch(str){
		case '*':yxj=5;break;
		case '/':yxj=5;break;
		case '+':yxj=4;break;
		case '-':yxj=4;break;
	}
	return yxj;
	
}
int main(){
	char c[100]="(12+4-13)+6*2";
	//char c[100]="1+((2+3)*4)-5";
	int lenc=strlen(c);
	//读取字符串 
	for(int i=0;i<lenc;i++){
		if(c[i]>='0'&&c[i]<='9'){		//若是是数字,直接压入s2 
			s2.push(c[i]);
		}else if(c[i]=='+'||c[i]=='-'||c[i]=='*'||c[i]=='/'){	//若是是运算符 
			while(true){
			if(s1.empty()||s1.top()=='('){		//s1为空 ,或者栈顶为( 
				s1.push(c[i]);
				break;
			}else if(f(c[i])>f(s1.top())){		//当前运算符优先级大于s1栈顶运算符优先级 
				s1.push(c[i]);
				break;
			}
			else{								//小于等于 
				char cc=s1.top();
				s1.pop();
				s2.push(cc);
			}
		}
		}else{
			if(c[i]=='('){			//直接读入 
				s1.push(c[i]);
			}else{
				while(s1.top()!='('){
					char ccc=s1.top();
					s1.pop();
					s2.push(ccc);
				}
				s1.pop();
			}
		}
	}
	while(!s1.empty()){
		char cccc=s1.top();
		s2.push(cccc);
		s1.pop();
	}
	
	//while(!s2.empty()){	//结果是逆序的 
	//	cout<<s2.top();
	//	s2.pop();
	//}
	while(!s2.empty()){
		char c=s2.top();
		s1.push(c);
		s2.pop();
	}
	while(!s1.empty()){	 
		cout<<s1.top();
		s1.pop();
	}
	
	return 0;
}