lua程序设计(第四版)练习答案自做(第二十一章)
程序员文章站
2022-07-07 20:16:01
...
21.1
#!/usr/bin/lua
Stack={}
function Stack:isempty()
return #self==0
end
function Stack:push(v)
table.insert(self,v)
end
function Stack:pop()
if #self~=0 then
table.remove(self)
else
error("Stack is empty")
end
end
function Stack:top()
if #self~=0 then
return self[#self]
else
return nil
end
end
function Stack:new(o)
o=o or {}
self.__index=self
setmetatable(o,self)
return o
end
---------------------
s=Stack:new({2})
print("top is "..s:top())
s:push(3)
print("top is "..s:top())
s:pop()
print("top is "..s:top())
s:pop()
if s:isempty() then
print("stack is empty!!!")
end
21.2
#!/usr/bin/lua
Stack={}
function Stack:isempty()
return #self==0
end
function Stack:push(v)
table.insert(self,v)
end
function Stack:pop()
if #self~=0 then
table.remove(self)
else
error("Stack is empty")
end
end
function Stack:top()
if #self~=0 then
return self[#self]
else
return nil
end
end
function Stack:new(o)
o=o or {}
self.__index=self
setmetatable(o,self)
return o
end
--以上是Stack类的定义
StackQueue=Stack:new()
function StackQueue:insertbottom(v)
table.insert(self,1,v)
end
--以上是StackQueue的定义
---------------------
s=StackQueue:new({2})
print("top is "..s:top())
s:push(3)
print("top is "..s:top())
s:insertbottom(5)
s:pop()
print("top is "..s:top())
s:pop()
print("bottom is "..s:top())
s:pop()
if s:isempty() then
print("stack is empty!!!")
end
21.3
#!/usr/bin/lua
local metadata={}
Stack={}
function Stack:isempty()
return #metadata[self]==0
end
function Stack:push(v)
table.insert(metadata[self],v)
end
function Stack:pop()
if #metadata[self]~=0 then
table.remove(metadata[self])
else
error("Stack is empty")
end
end
function Stack:top()
if #metadata[self]~=0 then
return metadata[self][#metadata[self]]
else
return nil
end
end
function Stack:new(o)
o=o or {}
self.__index=self
setmetatable(o,self)
metadata[o]={}
return o
end
---------------------
s=Stack:new()
s:push(3)
print("top is "..s:top())
s:push(4)
print("top is "..s:top())
s:pop()
s:pop()
if s:isempty() then
print("stack is empty!!!")
end
21.4
#!/usr/bin/lua
function newAccount(initialBalance)
local o={balance=initialBalance or 0}
local proxy={}
local mt={
balance=function ()
return o.balance
end,
withdraw=function (v)
o.balance=o.balance-v
end,
deposit=function (v)
o.balance=o.balance+v
end,
}
mt.__index=mt
setmetatable(proxy,mt)
return proxy
end
a=newAccount(103)
b=newAccount()
a.deposit(100.0)
b.withdraw(20)
print(a.balance())
print(b.balance())