forked from rosejn/lua-util
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqueue.lua
56 lines (44 loc) · 831 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
queue = {}
function queue.new()
return {left = 0,
right = -1}
end
function queue.is_empty(q)
if q.left > q.right then
return true
else
return false
end
end
function queue.push_left(q, v)
local left = q.left - 1
q.left = left
q[left] = v
return q
end
function queue.push_right(q, v)
local right = q.right + 1
q.right = right
q[right] = v
return q
end
function queue.pop_left(q)
local left = q.left
if queue.is_empty(q) then
return nil
end
local v = q[left]
q[left] = nil -- to allow garbage collection
q.left = left + 1
return v
end
function queue.pop_right(q)
local right = q.right
if queue.is_empty(q) then
return nil
end
local v = q[right]
q[right] = nil -- to allow garbage collection
q.right = right - 1
return v
end