1, from the left and right to the arithmetic expression scan, each read into a character s1[i];
2, if the number or decimal point encountered, then immediately write S2[i], if the arithmetic operator, "" (space) written to s2[i];
3, encountered the left parenthesis "(" then pressure stack;
4, if the arithmetic operators, if their priority than the top element of the stack, then directly into the stack, or pop-up stack top element output to S2[i], until the top element of the new stack is lower priority, and then press the stack;
5, if the right parenthesis ")", then the top element of the stack output to s2[i] until the top of the stack is "(", and then cancel each other; when the "#" symbol is scanned, the expression string is fully entered, all the operators in the stack are output to s2[i], and the top element of the stack is removed.
1 intIs_op (Charop)2 {3 Switch(OP)4{ Case '+':5 Case '-':6 Case '*':7 Case '/':return 1;8 default:return 0;9 }Ten } One /****************************/ A /*to determine the precedence of an operator*/ - /****************************/ - intPriorityCharop) the { - Switch(OP) - { - Case '(':return 0; + Case '+': - Case '-':return 1; + Case '*': A Case '/':return 2; at default:return-1; - } - } - - /*********************************/ - /*infix expression, converted to postfix expression*/ in /*********************************/ - voidPostfixCharE[],Charf[]) to {seqstack opst; + inti,j; -Initstack (&opst); thePush (&opst,' /'); *i=j=0; $ while(e[i]!=' /')Panax Notoginseng{if((e[i]>='0'&& e[i]<='9') || e[i]=='.') -F[j++]=e[i];/*Digital*/ the Else if(e[i]=='(')/*opening parenthesis*/ +Push (&opst,e[i]); A Else if(e[i]==')')/*closing parenthesis*/ the{ while(Stacktop (&opst)! ='(') +F[j++]=pop (&opst); -Pop (&OPST);/*' (' Out of the stack*/ $ } $ Else if(Is_op (E[i]))/*' +,-, *,/'*/ -{f[j++]=' ';/*two operands separated by a space*/ - while(Priority (Stacktop (&OPST)) >=Priority (E[i])) theF[j++]=pop (&opst); - WuyiPush (&opst,e[i]);/*current meta-stack*/ the } -i++;/*deal with the next dollar*/ Wu } - About while(!stackempty (&opst)) $F[j++]=pop (&opst); -f[j]=' /'; -}
An algorithm for converting infix expressions to postfix expressions