2016-11-14 39 views
0

我设法找到关于维基百科以下伪代码演示了如何使用调度场算法来创建一个定位后表达:如何使用分流码算法创建抽象树,而不是后缀表达式?

While there are tokens to be read: 
    Read a token. 
    If the token is a number, then push it to the output queue. 
    If the token is a function token, 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 operator 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 has precedence less than that of o2, 
      pop o2 off the operator stack, onto the output queue; 
    at the end of iteration push o1 onto the operator stack. 
If the token is a left parenthesis (i.e. "("), then push it onto the stack. 
If the token is a right parenthesis (i.e. ")"): 
    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. 

我如何修改这个算法来产生一个抽象语法树,什么我应该怎么做而不是推动操作员或操作数到输出?

+1

看一看[这里](http://softwareengineering.stackexchange.com/questions/254074/how-exactly-is-an-abstract-syntax-tree-created?rq=1)。 –

+0

谢谢,我只是做同样的事情,但把操作数推到表达式栈而不是输出。当一个操作符被推送到一个输出时,将栈顶的两个表达式连接起来? – user3102599

回答

0

我想描述使用分流码算法构建AST的最简单方法,但不是最有效的方法。 这个想法只是使用该算法构建一个后缀字符串,然后从后缀字符串构建AST,这非常简单。表达,例如:a * (b + c) + d

后缀串吧:

a b c + * d + 

让我们通过一个读取后缀串的一个标记。如果令牌是变量,则将其推送到具有节点的堆栈。如果它是一个操作数,让我们从堆栈中弹出包含节点的两个最高元素,创建另一个具有当前操作数的节点,并将两个提取的节点作为子节点。然后在节点堆栈中推新节点。

最后我们将只有一个节点留在节点堆栈中 - 树的根节点。树被修造。

该算法需要读取两次字符串,这是一个明显的缺点。另一方面,它非常简单。

更高效的算法,无需构建后缀字符串,但立即使用分流码算法构建AST,这里描述如下:but it's in C++