Stack Data Structure

How Stack Works

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. Elements are added to and removed from the same end, called the top of the stack.

Key operations:

  • Push: Adds an element to the top of the stack
  • Pop: Removes and returns the top element from the stack
  • Peek: Returns the top element without removing it

Time complexities:

  • Push: O(1)
  • Pop: O(1)
  • Peek: O(1)

Stacks are used in many applications, including function call management in programming languages, undo mechanisms in text editors, and in algorithms like depth-first search.

class Stack:
    items

    function push(element):
        items.append(element)
        visualize()

    function pop():
        if isEmpty():
            return null
        element = items.pop()
        visualize()
        return element

    function peek():
        if isEmpty():
            return null
        return items[items.length - 1]

    function isEmpty():
        return items.length == 0