Skip to content
本站總訪問量
本站訪客數 人次

前序運算式

輸入 中序 輸出 前序

python
st = input()
level = {'+': 1, '-': 1, '*': 2, '/': 2}

output = []
stack = []

for char in reversed(st):  # 反轉輸入字串,改為從右到左處理
    if char.isalnum():
        output.append(char)
    elif char == ')':
        stack.append(char)
    elif char == '(':
        while stack and stack[-1] != ')':
            output.append(stack.pop())
        stack.pop()
    elif char in '+-*/':
        while (stack and (stack[-1] in '+-*/') and (level[stack[-1]] > level[char])):
            output.append(stack.pop())
        stack.append(char)

while stack:
    output.append(stack.pop())

print(''.join(reversed(output)))  # 最終結果需要再次反轉以得到正確的前序表達式

Contributors

The avatar of contributor named as lucashsu95 lucashsu95

Changelog