Created
October 8, 2018 23:10
-
-
Save echiesse/4d27ec4476dae78b26ab4fa7d097eb96 to your computer and use it in GitHub Desktop.
Basic queue data structure implementation in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverse(tb) | |
local ret = {} | |
for i = #tb, 1, -1 do | |
table.insert(ret, tb[i]) | |
end | |
return ret | |
end | |
--############################################################################## | |
local Node = {} | |
function Node.create(val, prev) | |
return {val = val, prev = prev} | |
end | |
--############################################################################## | |
queue = {} | |
function queue.create() | |
local mt = | |
{ | |
__index = queue, | |
__tostring = queue.show, | |
} | |
local q = | |
{ | |
init = nil, | |
last = nil, | |
} | |
return setmetatable(q, mt) | |
end | |
function queue.insert(q, val) | |
local node = Node.create(val) | |
if q.init == nil then -- => queue is empty | |
q.last = node | |
else | |
q.init.prev = node | |
end | |
q.init = node | |
return q | |
end | |
function queue.pop(q) | |
local ret = q.last.val | |
q.last = q.last.prev | |
return ret | |
end | |
function queue.show(q) | |
local nodes = {} | |
local it = q.last | |
while it ~= nil do | |
table.insert(nodes, it.val) | |
it = it.prev | |
end | |
nodes = reverse(nodes) | |
for i, node in ipairs(nodes) do | |
nodes[i] = '{'.. tostring(node) .. '}' | |
end | |
return table.concat(nodes, '<-') | |
end | |
--############################################################################## | |
function showtable(tb) | |
local aux = {} | |
for i, v in ipairs(tb) do | |
table.insert(aux, tostring(v)) | |
end | |
local parts = {'[', table.concat(aux, ', '), ']'} | |
return table.concat(parts) | |
end | |
function test() | |
local q = queue.create() | |
:insert(1) | |
:insert(2) | |
:insert(10) | |
--print(q:show()) | |
print(q) | |
print(q:pop()) | |
print(q:pop()) | |
print(q:pop()) | |
end | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment