利用栈实现汉诺塔的调用。并在主函数中进行测试。要求: (1)定义栈以及栈的型。 (2)定义栈的各种操作。 (3)实现函数hanoi0。 (4)在main西数中,通过调用函数hanoi(3,a.b,c)
时间: 2023-05-17 16:05:03 浏览: 46
以下是利用栈实现汉诺塔的调用的代码:
```lua
-- 定义栈
local Stack = {}
Stack.__index = Stack
function Stack:new()
local stack = {top = 0}
setmetatable(stack, self)
return stack
end
function Stack:push(value)
self.top = self.top + 1
self[self.top] = value
end
function Stack:pop()
if self.top == 0 then
return nil
end
local value = self[self.top]
self[self.top] = nil
self.top = self.top - 1
return value
end
function Stack:is_empty()
return self.top == 0
end
function Stack:size()
return self.top
end
function Stack:top_value()
if self.top == 0 then
return nil
end
return self[self.top]
end
-- 实现函数hanoi0
function hanoi0(n, from, to, via)
if n == 1 then
print("Move disk 1 from " .. from .. " to " .. to)
return
end
hanoi0(n - 1, from, via, to)
print("Move disk " .. n .. " from " .. from .. " to " .. to)
hanoi0(n - 1, via, to, from)
end
-- 实现函数hanoi
function hanoi(n, from, to, via)
local stack = Stack:new()
stack:push({n, from, to, via})
while not stack:is_empty() do
local args = stack:pop()
local n, from, to, via = args[1], args[2], args[3], args[4]
if n == 1 then
print("Move disk 1 from " .. from .. " to " .. to)
else
stack:push({n - 1, via, to, from})
stack:push({1, from, to, via})
stack:push({n - 1, from, via, to})
end
end
end
-- 在main函数中测试
hanoi0(3, "A", "C", "B")
hanoi(3, "A", "C", "B")
```
输出结果为:
```
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
```
```
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
```
阅读全文