Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.lua
local function render(values)
local parts = {}
for i, value in ipairs(values) do parts[i] = tostring(value) end
return table.concat(parts, " -> ")
end
local queue = {}
for _, value in ipairs({10, 20, 30}) do table.insert(queue, value) end
local removed = {}
while #queue > 0 do table.insert(removed, table.remove(queue, 1)) end
print(render(removed))
Complexity
- Time: O(n) per front dequeue here because
table.remove(queue, 1)shifts the dense table; O(1) per operation with a real queue - Space: O(n)
Implementation notes
local queue = {}starts as an empty Lua table, and the trace records[].- Enqueue uses
table.insert(queue, value)while iteratingipairs({10, 20, 30}), so values append at the back in that order. - After enqueue, the queue state is
[10, 20, 30]. - Lua's front position here is index
1; dequeue usestable.remove(queue, 1). table.remove(queue, 1)returns the removed front value and shifts the remaining dense-table values left.- Removed values are collected with
table.insert(removed, ...). - The first dequeue returns
10, leavingqueue = [20, 30]andremoved = [10]. - The remaining dequeues return
20and30, leavingqueue = []andremoved = [10, 20, 30]. render(removed)usesipairsandtable.concat(parts, " -> "), soprint(render(removed))outputs10 -> 20 -> 30.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.