stack = {}
function stack:isEmpty()
return #self == 0
end
function stack:push(v)
table.insert(self, v)
end
function stack:pop(v)
if #self > 0 then
table.remove(self, v)
else
error("self 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
stack = {}
function stack:isEmpty()
return #self == 0
end
function stack:push(v)
table.insert(self, v)
end
function stack:pop(v)
if #self > 0 then
table.remove(self, v)
else
error("self 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
stackQueue = stack:new{}
function stackQueue:insertbottom(v)
table.insert(self, 1, v)
end
s = stackQueue:new{}
print(s:insertbottom(2)) -- {2}
练习3. 使用对偶表示重新实现类Stack
stack = {}
local balance = {}
function stack:isEmpty()
return #balance[self] == 0
end
function stack:push(v)
table.insert(balance[self], v)
end
function stack:pop(v)
if #balance[self] > 0 then
table.remove(balance[self], v)
else
error("self is Empty")
end
end
function stack:top()
if #balance[self] > 0 then
return balance[self][#balance[self]]
else
return nil
end
end
function stack:new(o)
o = o or {}
self.__index = self
setmetatable(o, self)
balance[0] = {}
return o
end