-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqueue.lua
67 lines (61 loc) · 1011 Bytes
/
queue.lua
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
local function push(self, v)
self[self.tail] = v
self.tail = self.tail + 1
end
local function pop(self)
if self.head == self.tail then
self.head = 1
self.tail = 1
return nil
else
local r = self[self.head]
self[self.head] = nil
self.head = self.head + 1
return r
end
end
local function head(self)
if self.head == self.tail then
self.head = 1
self.tail = 1
return nil
else
return self[self.head]
end
end
local function tail(self)
if self.head == self.tail then
self.head = 1
self.tail = 1
return nil
else
return self[self.tail]
end
end
local function size(self)
if self.tail - self.head <= 0 then
return 0
else
return self.tail - self.head
end
end
local function create()
local q = {head = 1, tail = 1}
q.push = push
q.pop = pop
q.size = size
q.head = head
q.tail = tail
return q
end
return create
--[[
local q = require("queue")()
q:push(1)
q:push(2)
q:push(3)
assert(q:size() == 3)
assert(q:pop() == 1)
assert(q:pop() == 2)
assert(q:pop() == 3)
--]]