Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-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 stack = {}
for _, value in ipairs({10, 20, 30}) do table.insert(stack, value) end
local popped = {}
while #stack > 0 do table.insert(popped, table.remove(stack)) end
print(render(popped))
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
local stack = {}starts as an empty Lua table, and the trace records[].- Pushes iterate
ipairs({10, 20, 30})and usetable.insert(stack, value). - In this source, the stack top is the end of the table, so after the pushes
the top value is
30in[10, 20, 30]. - The pop loop runs while
#stack > 0. - Bare
table.remove(stack)removes and returns the last table value. - Removed values are collected with
table.insert(popped, table.remove(stack)). - The first pop returns
30, leavingstack = [10, 20]andpopped = [30]. - The remaining pops return
20and then10, ending withpopped = [30, 20, 10]andstack = []. render(popped)usesipairsandtable.concat(parts, " -> "), soprint(render(popped))outputs30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.