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.rb
stack = []
[10, 20, 30].each { |value| stack.push(value) }
popped = []
popped << stack.pop until stack.empty?
puts popped.join(" -> ")
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- The stack is a Ruby
Array, starting asstack = []. - Push uses
stack.push(value)for10,20, and30, so the top is the array's last element. - Pop uses
stack.pop, which removes and returns that last element while mutating the same array. popped << stack.pop until stack.empty?records each returned value and stops before an empty pop could returnnil.- The trace shows LIFO order directly:
[10, 20, 30]pops30first, then20, then10. - After all pops,
stackis[]andpoppedis[30, 20, 10]. puts popped.join(" -> ")prints30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.