Infix expression-to-suffix expression method:
1. Operand encountered: Direct output (added to suffix expression)
2. When the stack is empty, the operator is encountered, directly into the stack
3. An opening parenthesis is encountered: put it in the stack
4. A closing parenthesis is encountered: Performs a stack operation, and outputs the elements of the stack, until the left parenthesis of the pop-up stack, and the left parenthesis does not output.
5. Other operators encountered: subtraction: POPs all top-level elements with precedence greater than or equal to the operator, and then stacks the operator into the stack
6. Finally, the elements in the stack are sequentially out of the stack and output.
Pat: Expression conversion (25)
1#include <stdio.h>2#include <stack>3#include <ctype.h>4 using namespacestd;5 intp[ -];6 intPriority (CharACharb) {//judging the priority level7 if(a=='(')return 0;8 if(P[a]<p[b])return 0;9 if(P[a]>=p[b])return 1;Ten } One intMain () { A Chars[ -],ans[ -],tmp[ -]; - inti; -stack<Char> st;//stack, used to store operators thep['+']=p['-']=1;//setting the priority level -p['*']=p['/']=2; - while(SCANF ("%s", s)! =EOF) { - intj=0, k=0;//J: The pointer to the answer; K: Mark + for(i=0; s[i];i++){ - if(s[i]=='(')//left parenthesis directly into the stack + St.push (S[i]); A Else if(s[i]==')'){//output The symbol behind the opening parenthesis sequentially at if(k) { -ans[j++]=' '; -k=0; - } - while(St.top ()! ='('){ -ans[j++]=st.top (); inans[j++]=' '; - St.pop (); to } +St.pop ();//Remove opening parenthesis - } the Else if(s[i]>='0'&&s[i]<='9'|| s[i]=='.'){//numbers, including decimals *ans[j++]=S[i]; $k=1;Panax Notoginseng } - Else{// +-*/ the if(k) {//if k==1, the description is preceded by a number, add a space, and reset the K +ans[j++]=' '; Ak=0; the } + if((s[i]=='+'|| s[i]=='-') &&i==0){//plus sign 1 - if(s[i]=='-') $ans[j++]=S[i]; $ Continue; - } - if((s[i]=='+'|| s[i]=='-') &&i!=0&&s[i-1]=='('){//plus sign 2 the if(s[i]=='-') ans[j++]=S[i]; - St.pop ();Wuyi while(s[++i]!=')'){//the right parenthesis here should be handled specially. theans[j++]=S[i]; - } Wuans[j++]=' '; - Continue; About } $ while(!st.empty () &&priority (St.top (), s[i]) {//pops all the top elements of the stack that have precedence greater than or equal to the operator, and then put the operator into the stack -ans[j++]=st.top (); -ans[j++]=' '; - St.pop (); A } + St.push (S[i]); the } - } $ if(k) { theans[j++]=' '; thek=0; the } the while(!st.empty ()) {//last popup all operators -ans[j++]=st.top (); inans[j++]=' '; the St.pop (); the } Aboutans[j-1]=0;//remove the last space the puts (ans); the } the return 0; +}
Infix expression-to-suffix expression