-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex21.2.lua
More file actions
50 lines (40 loc) · 909 Bytes
/
ex21.2.lua
File metadata and controls
50 lines (40 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
local Stack = { data = {} }
Stack.__index = Stack
function Stack:new(o)
o = o or {}
setmetatable(o, Stack)
return o
end
function Stack:is_empty()
return #self.data == 0
end
function Stack:push(e)
table.insert(self.data, e)
end
function Stack:pop(e)
assert(not self:is_empty())
table.remove(self.data, e)
end
function Stack:top()
assert(not self:is_empty())
return self.data[#self.data]
end
local StackQueue = Stack:new()
StackQueue.__index = StackQueue
function StackQueue:new(o)
o = o or {}
setmetatable(o, StackQueue)
return o
end
function StackQueue:insert_bottom(e)
table.insert(self.data, 1, e)
end
local my_queue = StackQueue:new()
assert(my_queue:is_empty())
my_queue:push(1)
my_queue:insert_bottom(2)
assert(my_queue:top() == 1)
my_queue:pop()
assert(my_queue:top() == 2)
my_queue:pop()
assert(my_queue:is_empty())