Infix Experssion | Prefix Expression | Postfix Expression |
---|---|---|
A + B * C | +A * B C | A B * C + |
(A + B) * C | +A B * C | A B + C * |
Only infix expression need parentheses.
Steps for converting infix expression to postfix expression
-
1.Create an empty stack for keeping operators. Create an empty list for output.创建一个空的栈去保存运算符,并创建一个空的列表用来保存输出。 2.Convert the input infix string to a list by using the string method split.将输入的infix类型的字符串用string的split方法将其转变为列表。 3.Scan the token list from left to right.从左向右扫描这个列表。
- If the token is an operand, append it to the end of the output list. 如果从string列表中取出的是运算元,并将其放入保存输出的列表当中。
- If the token is a left parenthesis, push it on the stack.如果从列表中取出的是左括号,那么将其放入栈中。
- If the token is a right parenthesis, pop the stack until the corresponding left parenthesis is removed. Append each operator to the end of the output list.如果从列表中取出的是右括号,那么对栈使用pop方法直到与之相对应的左括号被移出。将括号间的所有运算符一一放入保存输出的列表中。
- If the token is an