lua实现中缀转后缀

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 )"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值