Skip to content
thesarfo

Reference

Stack: LIFO Operations

How a stack's push, pop, and peek operations work, tracked with a TOP pointer.

views 0

A stack is a linear data structure that follows Last In First Out (LIFO): the last element inserted is the first one removed.

Stack Operations

  • Push — add an element to the top of the stack.
  • Pop — remove an element from the top of the stack.
  • IsEmpty — check if the stack is empty.
  • IsFull — check if the stack is full.
  • Peek — get the value of the top element without removing it.

Working of a Stack

  1. A pointer called TOP tracks the top element of the stack.
  2. When initializing the stack, TOP is set to -1, so TOP == -1 means empty.
  3. On pushing, TOP is incremented and the new element is placed at the position it points to.
  4. On popping, the element at TOP is returned and TOP is decremented.
  5. Before pushing, check if the stack is already full.
  6. Before popping, check if the stack is already empty.

For the array-based implementation, push and pop both take constant time — O(1).