lua 逆波兰表达式实现的方法
上一篇 /
下一篇 2012-11-11 03:01:15
/ 个人分类:lua
--将算术表达式转化为后缀表达式
function trans(str)
local stack = {} --/*作为临时栈使用*/
local ex = {} --逆波兰表达式(后缀表达式)
--拆分原表达式
local tabStr = split_str(str)
--表达式添加#后缀
table.insert(tabStr,"#")
local t = 1 -- 作为后缀表达式表下标指针
local top = 0 --作为栈指针使用
local i = 1 --作为原算术表达式下标指针
local ch = tabStr[i]
i = i + 1
while ch ~= "#" do
if ch == "(" then
--判定符号为左括号,直接压入栈内
top = top + 1
stack[top] = ch
elseif ch == ")" then
--判定为右括号,取出栈内符号,直到遇到左括号
while stack[top] ~= "(" do
ex[t] = stack[top]
t = t + 1
top = top - 1
end
--top指向的左括号减1(目的去掉栈内左括号)
top = top - 1
elseif ch == "+" or ch == "-" then
--如果+ 或者 - 不是栈底或者前面不是左括号的时候,输出符号
while top ~= 0 and stack[top] ~= "(" do
ex[t] = stack[top]
t = t + 1
top = top - 1
end
--符号压入栈内
top = top + 1
stack[top] = ch
elseif ch == "*" or ch == "/" then
--优先级判断,如果栈前是乘除,则输出
while stack[top] == "*" or stack[top] == "/" do
ex[t] = stack[top]
t = t + 1
top = top - 1
end
--符号压入栈内
top = top + 1
stack[top] = ch
elseif ch == " " then
else
--判定为数字,直接插入后缀表
while ch >= "0" and ch <= "9" do
ex[t] = ch
t= t + 1
ch = tabStr[i]
i = i + 1
end
--数字输出完毕后加上空格
i = i - 1
ex[t] = " "
t= t + 1
end
ch = tabStr[i]
i = i + 1
end
--循环字符串结束后,输出栈内剩余符号
while top ~= 0 do
ex[t]=stack[top]
t = t + 1
top = top - 1
end
ex[t]=' '
--后缀表达式已经转换完毕
return ex
end
--计算后缀表达式
function compute_value(ex_tab)
local stack = {} --临时栈使用
local d -- 数字换算使用
local t = 1
local top = 0 --t 为ex下标 top 为stack下标
local ch = ex_tab[t]
t = t + 1
while ch ~= " " do
if ch == "+" then
stack[top-1] = stack[top-1] + stack[top]
top = top - 1
elseif ch == "-" then
stack[top-1] = stack[top-1] - stack[top]
top = top - 1
elseif ch == "*" then
stack[top-1] = stack[top-1] * stack[top]
top = top - 1
elseif ch == "/" then
if stack[top] ~= 0 then
stack[top-1] = stack[top-1] / stack[top]
top = top - 1
else
print("异常:除0错误")
end
else
--如果是数字字符转换为对应数值
d = 0
while ch >= "0" and ch <= "9" do
d = d * 10 + ch - "0" --数字字符转换为对应数值
ch = ex_tab[t]
t = t + 1
end
top = top + 1
stack[top] = d
end
ch = ex_tab[t]
t = t + 1
end
return stack[top]
end
--拆分字符串
function split_str(str)
local tab_str = {}
while true do
local str_len = string.len(str)
if str_len ~= 1 then
local v_str = string.sub(str,1,1)
table.insert(tab_str,v_str)
str = string.sub(str,2,str_len)
else
table.insert(tab_str,str)
return tab_str
end
end
end
收藏
举报
TAG: