由于后缀表达式求值比较容易,一个下推栈即可,所以在编译过程中,中缀表达式会转成后缀表达式,简单算法如下:
中缀表达式转换为后缀表达式(逆波兰表达式),即调度场算法(shunting yard algorithm)
1.建立运算符栈用于运算符的存储,此运算符遵循越往栈顶优先级越高的原则。
2.预处理表达式,正、负号前加0(如果一个加号(减号)出现在最前面或左括号后面,则该加号(减号) 为正负号)。
3.顺序扫描表达式,如果当前字符是数字(优先级为0的符号),则直接输出该数字;如果当前字符为运算符或者括号(优先级不为0的符号),则判断第四点。
4.若当前运算符为'(',直接入栈;
若为')',出栈并顺序输出运算符直到遇到第一个'(',遇到的第一个'('出栈但不输出;
若为其它,比较运算符栈栈顶元素与当前元素的优先级:
如果栈顶元素是'(',当前元素直接入栈;
如果栈顶元素优先级>=当前元素优先级,出栈并顺序输出运算符直到栈顶元素优先级<当前元素优先级,然后当前元素入栈;
如果栈顶元素优先级<当前元素优先级,当前元素直接入栈。
5.重复第三点直到表达式扫描完毕。
6.顺序出栈并输出运算符直到栈元素为空。
下面给出英文版本:
- While there are tokens to be read:
-
- Read a token.
- If the token is a number, then add it to the output queue.
- If the token is a functiontoken, then push it onto the stack.
- If the token is a function argument separator (e.g., a comma):
-
- Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. If no left parentheses are encountered, either the separator was misplaced or parentheses were mismatched.
- If the token is an operator, o1, then:
-
- while there is an operator token, o2, at the top of the stack, and
- either o1 is left-associative and its precedence is less than or equal to that of o2,
- or o1 is right-associative and its precedence is less than that of o2,
- pop o2 off the stack, onto the output queue;
- push o1 onto the stack.
- If the token is a left parenthesis, then push it onto the stack.
- If the token is a right parenthesis:
-
- Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue.
- Pop the left parenthesis from the stack, but not onto the output queue.
- If the token at the top of the stack is a function token, pop it onto the output queue.
- If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.
- When there are no more tokens to read:
-
- While there are still operator tokens in the stack:
-
- If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses.
- Pop the operator onto the output queue.
- Exit.
浙公网安备 33010602011771号