function infixToPostfix(expression) -- 中缀表达式转后缀表达式
local operators = { -- 定义运算符的优先级
["+"] = 0, -- 加法
["-"] = 0, -- 减法
["*"] = 1, -- 乘法
["/"] = 1, -- 除法
}
local postfix = {} -- 存储后缀表达式
local stack = {} -- 栈用于中间计算
function popStackAndAppendToPostfix()
local top = table.remove(stack) -- 弹出栈顶元素
while top do
table.insert(postfix, top) -- 将弹出的元素放入后缀表达式
top = table.remove(stack) -- 继续弹出栈顶元素
end
end
for token in expression:gmatch("%S+") do -- 分离表达式中的各个标记(运算符、数字或括号)
local isOperator = operators[token] -- 检查是否为算术运算符
if isOperator then
while #stack > 0 and operators[stack[#stack]] and operators[token] <= operators[stack[#stack]] do
-- 若栈非空且栈顶为算术运算符,并且当前运算符的优先级小于等于栈顶运算符的优先级
table.insert(postfix, table.remove(stack)) -- 弹出栈顶元素并加入后缀表达式
end
table.insert(stack, token) -- 将当前运算符入栈
elseif token == "(" then
table.insert(stack, token) -- 左括号直接入栈
elseif token == ")" then
local top = table.remove(stack) -- 弹出栈顶元素
while top and top ~= "(" do
table.insert(postfix, top) -- 弹出的元素加入后缀表达式
top = table.remove(stack) -- 继续弹出栈顶元素
end
else
table.insert(postfix, token) -- 数字直接加入后缀表达式
end
end
popStackAndAppendToPostfix() -- 弹出栈中剩余元素并加入后缀表达式
return table.concat(postfix, " ") -- 返回后缀表达式的字符串形式
end
-- 测试示例
print(infixToPostfix("3 + 4 * 2 / ( 1 - 5 )"))