我一直在嘗試實作分流碼演算法,但我的決議器的輸出不正確。
let mut stack: Vec<String> = vec![];
let mut op_stack: Vec<String> = vec![];
for current in sub_tree {
if current.tok_type == TokenType::NUMBER || current.tok_type == TokenType::NEGNUMBER {
self.parse();
stack.push(current.content.clone());
}
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
}
我正在決議的原始方程: 1 2 * 3
我期望以下輸出: 1 2 3 *
相反,我得到了這個: 1 2 3 *
我想我在 while 回圈中的某個地方出錯了,但我真的不知道。我試圖按照維基百科文章中的例子進行操作。
uj5u.com熱心網友回復:
我忘記了最后我必須從運算子堆疊彈出回輸出堆疊。
uj5u.com熱心網友回復:
比較你的代碼
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
使用維基百科代碼https://en.wikipedia.org/wiki/Shunting-yard_algorithm
- an operator o1:
while (
there is an operator o2 other than the left parenthesis at the top
of the operator stack, and (o2 has greater precedence than o1
or they have the same precedence and o1 is left-associative)
):
pop o2 from the operator stack into the output queue
push o1 onto the operator stack
看起來它們在功能上是相同的。
所以我懷疑問題不在于代碼,而在于優先級表。如果你有 和 * 的優先級錯誤,那么你會得到這種行為。很容易混淆這一點,因為某些來源具有從更緊密系結到失敗者的優先級,而有些則相反。比較維基百科的操作順序 和Java 中的運算符優先級,使用前者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394024.html
上一篇:JObject不決議我需要的值
