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.swift
func render(_ values: [Int]) -> String {
values.map(String.init).joined(separator: " -> ")
}
var stack: [Int] = []
for value in [10, 20, 30] { stack.append(value) }
var popped: [Int] = []
while !stack.isEmpty { popped.append(stack.removeLast()) }
print(render(popped))
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
var stack: [Int] = []is a mutable Swift array used as stack storage, with the back of the array acting as the top.- The push loop
for value in [10, 20, 30] { stack.append(value) }appends eachIntin order, producing[10, 20, 30]. var popped: [Int] = []records pop order separately from the remaining stack.- The loop guard
while !stack.isEmptyprevents callingremoveLast()on an empty array, so this source has no optional return or sentinel path. popped.append(stack.removeLast())removes from the array end, so30is recorded before20and10.- The trace shows the stack moving from
[]to[10, 20, 30], then the first pop producingpopped = [30]andstack = [10, 20], and finallypopped = [30, 20, 10]withstack = []. render(_:)maps eachInttoStringand joins with" -> ", 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.