/*该程序只能输入0-9的字符和四则运算符以及左右括号!
有知识性的问题不懂的可以私聊,
或者也可以先保留问题:后续更新会陆续补上相关知识点问题!*/
//中缀表达式转为后缀表达式 #include<iostream> using namespace std; typedef struct { char *top; char *base; int size; }stack; void init(stack &S) { S.base=new char[20]; S.top=S.base; S.size=20; } void push(stack &S,char e) { if(S.top-S.base==S.size) exit(0); *S.top++=e; } void pop(stack &S,char &e) { if(S.base==S.top) exit(0); e=*--S.top; } //+-*/() char precede(char a,char b) { if(a=='+'||a=='-') { if(b=='+'||b=='-'||b==')') return '>';//a>b else return '<'; } else if(a=='*'||a=='/') { if(b=='(') return '<'; else return '>'; } else { if(b==')') return '='; else return '<'; } } char gettop(stack &S) { if(S.base!=S.top) return *(S.top-1); } void show(stack &S,int n) { char e; for(int i=0;i<n;i++) { pop(S,e); cout<<e<<" "; } cout<<endl; } int main() { stack S; init(S); int i=0; char a; string e; cin>>e; while(e[i]!='\0') { if(e[i]>='0'&&e[i]<='9') cout<<e[i]; else { int flag=1; while(flag) { if(S.base==S.top) { if(e[i]==')'); else push(S,e[i]); //cout << "top=" <<gettop(S)<< endl; flag=0; } else { if(precede(*(S.top-1),e[i])=='<') { push(S,e[i]); flag=0; } else if(precede(*(S.top-1),e[i])=='>') { //cout << "ggg" << endl; pop(S,a);//弹出,并继续比较 cout<<a; } else { pop(S,a); } } } } i++; } //show(S,9); while(S.base!=S.top) { pop(S,a); cout<<a; } } //2*3+5*(3-2)+6 //2+3+5*6-(8+2)-6/2