使用堆疊(stack)轉換中序運算式(infix)到後序運算式(postfix)的演算法涉及對運算式的每個字元進行迭代處理,使用一個堆疊來處理運算子,並建立一個輸出串列來形成後序運算式。以下是轉換演算法的步驟:
創建一個堆疊來存放運算子,以及一個列表來存放後序運算式的結果。
從左到右讀取中序運算式的每個字元。
如果讀到的是操作數(數字或變數),直接將其加入到後序列表中。
如果讀到的是左括號 (,將其推入堆疊中。
如果讀到的是右括號 ),則從堆疊中彈出運算子並加入到後序列表中,直到遇到左括號為止。彈出左括號,但不將其加入到後序列表中。
如果讀到的是運算子(例如 +, -, *, /),則:
從堆疊中彈出所有優先級高於或等於當前運算子的運算子。
將彈出的運算子加入到後序列表中。
將當前讀到的運算子推入堆疊中。
如果讀取完畢,將堆疊中剩餘的運算子依次彈出並加入到後序列表中。
最終,後序列表將表示運算式的後序形式。
這裡是一個轉換中序到後序運算式的偽代碼示例:
pseudo
Copy code
function infixToPostfix(infixExpression):
define operators to be a map with operator precedence
initialize an empty stack operatorStack
initialize an empty list postfixList
for each token in infixExpression:
if token is an operand:
append token to postfixList
else if token is a left parenthesis '(':
push token onto operatorStack
else if token is a right parenthesis ')':
while the top of operatorStack is not a left parenthesis:
append the top of operatorStack to postfixList
pop the operatorStack
pop the operatorStack // Pop the left parenthesis
else if token is an operator:
while (operatorStack is not empty) and
(precedence of the top of operatorStack >= precedence of token):
append the top of operatorStack to postfixList
pop the operatorStack
push token onto operatorStack
// No more tokens to read
while operatorStack is not empty:
append the top of operatorStack to postfixList
pop the operatorStack
return postfixList
在這個偽代碼中,“操作數”假定為任何非運算子和非括號的字元,而“運算子”包括所有數學運算子。你需要為具體實現定義運算子的優先級。實際代碼實現中,你還需確保處理負數和多位數等情況。