Stacks

A stack is a fundamental data structure that follows the Last-In-First-Out (LIFO) principle. One way to think about a stack is to compare it to a Pez Dispenser holding Pez candies. If you’re unfamiliar with a Pez Dispenser, it’s a spring-loaded container that looks like this: It holds small, brick-shaped candies: To use the dispenser, you open the top and insert the candies, compressing the spring. Once closed, you can tilt the top to dispense one candy at a time. The stack works similarly.

There are two essential operations when working with a stack: push and pop. The push operation adds an element to the top of the stack. The pop operation removes the top element from the stack.

Below is a Swift implementation of a stack using generics and an array. This allows the stack to store any data type while leveraging Swift’s built-in append and popLast functions, enabling push and pop operations to run in O(1) time complexity.

public struct Stack<Element> {
	private var stack: [Element] = []
	public init() { }
	public mutating func push(_ element: Element) {
		stack.append(element)
	}
	public mutating func pop() -> Element? {
		stack.popLast()
	}
	public var isEmpty: Bool { // Convenience Computed Variable
		stack.isEmpty
	}
}

Tags: tech, data_structures_algorithms