#!/usr/local/bin/lua
function deque()
local queue = { first = 0, last = -1 }
local obj = {}
function obj.push_front(data)
local first = queue.first - 1
queue.first = first
queue[first] = data
end
function obj.pop_front()
local first = queue.first
if first > queue.last then
error("deque is empty")
end
local data = queue[first]
queue[first] = nil
queue.first = first + 1
return data
end
function obj.push_back(data)
local last = queue.last + 1
queue.last = last
queue[last] = data
end
function obj.pop_back()
local last = queue.last
if last < queue.first then
error("deque is empty")
end
local data = queue[last]
queue[last] = nil
queue.last = queue.last - 1
return data
end
function obj.size()
return queue.last - queue.first + 1
end
function obj.print()
local t = {}
for i = queue.first, queue.last do
t[#t + 1] = queue[i]
end
local s = table.concat(t, ", ")
print(s)
end
return obj
end
local deque = deque()
deque.push_front(1)
deque.push_back(2)
deque.pop_front()
deque.pop_back()