Stack Simulator

A stack is a Last-In, First-Out (LIFO) data structure. Elements are inserted and removed only from the top. The most recently pushed element is therefore the first element to be popped.

PushO(1)
PopO(1)
PeekO(1)
SearchO(n)

Stack operations

350 ms
BottomTop
TOP

Use the controls to inspect or modify the stack.

Operation history

    push(x):
      stack[top + 1] = x
      top = top + 1
    
    pop():
      x = stack[top]
      top = top - 1
      return x
    Current operationIdle
    Elements checked0
    Size0
    Complexity—

    Stack concepts

    LIFO discipline

    The last element inserted is the first one removed. Only the top is directly accessible.

    Constant-time top operations

    Push, pop, and peek only affect the top position, so each takes O(1).

    Searching

    A search may inspect every element from the top downward, giving O(n) worst-case time.

    Common uses

    Stacks are used for function calls, undo/redo, expression evaluation, and depth-first search.

    Typical time complexities

    OperationTimeReason
    PushO(1)Add one element at the top.
    PopO(1)Remove one element from the top.
    PeekO(1)Read the current top element.
    SearchO(n)Elements may be checked from top to bottom.
    SpaceO(n)One storage position is needed per element.