Sobes.tech
Junior

What is a stack data structure and how does it work?

sobes.tech AI

Answer from AI

Stack — is a linear data structure that operates on the LIFO (Last-In, First-Out) principle, where the last added element is the first to be removed.

Main operations:

  • Push: Adding an element to the top of the stack.
  • Pop: Removing and returning the top element of the stack.
  • Peek/Top: Viewing the top element without removing it.
  • isEmpty: Checking if the stack is empty.
  • size: Getting the number of elements in the stack.

Example implementation in Swift:

// Simple stack implementation using an array
struct Stack<Element> {
    private var elements: [Element] = []

    // Add an element
    mutating func push(_ element: Element) {
        elements.append(element)
    }

    // Remove and return an element
    mutating func pop() -> Element? {
        elements.popLast() // popLast is convenient for LIFO
    }

    // View the top element
    func peek() -> Element? {
        elements.last // last is convenient for LIFO
    }

    // Check if empty
    var isEmpty: Bool {
        elements.isEmpty
    }

    // Stack size
    var size: Int {
        elements.count
    }
}

// Usage example
var myStack = Stack<Int>()
myStack.push(1)
myStack.push(2)
myStack.push(3)

print(myStack.pop() ?? "Stack is empty") // Output: 3
print(myStack.peek() ?? "Stack is empty") // Output: 2
print(myStack.size) // Output: 2
print(myStack.isEmpty) // Output: false

Applications in iOS development:

  • Managing navigation in UINavigationController (pushViewController, popViewController).
  • Call stack of functions.
  • Handling action history (Undo/Redo).
  • Parsing expressions (e.g., in compiler work).
What is a stack data structure and how does it work… - sobes.tech