AlgoDocs

Operations on Stack

Key operations performed on a stack data structure

Operations

The stack data structure supports several key operations that allow us to manipulate the elements within it. These operations include:

  1. Push: Add an element to the top of the stack.
  2. Pop: Remove the top element from the stack.
  3. Peek/Top: View the top element without removing it.
  4. IsEmpty: Check if the stack is empty.
  5. IsFull: Check if the stack is full (relevant for fixed-size stacks).

Push

In Push operation, we add an element to the top of the stack. The stack follows the Last In First Out (LIFO) principle, meaning the last element added is the first one to be removed.

Adding an element to the top of the stack.

  • Before adding an element to the stack, we check if the stack is full.

  • If the stack is full (top==capacity-1), we get a Stack Overflow and cannot add any more elements.

  • If the stack isn't full, we increase the top by 1 (top = top + 1) and insert the new element at that position.

  • We can keep adding elements until the stack reaches its capacity.

Visualization of Push Operation On Stack

Pop

In Pop operation, we remove the top element from the stack. If the stack is empty, we cannot remove any elements.

Removing the top element from the stack.

  • Before removing an element from the stack, we check if it’s empty.

  • If the stack is empty (top==-1), we can't remove anything, which is called Stack Underflow.

  • If the stack has elements, we get the value at the top, move the top down by 1, and return the value we retrieved.

Visualization of Pop Operation On Stack

Peek/Top

In Peek or Top operation, we view the top element of the stack without removing it. This is useful when we want to check what the last added element is without modifying the stack.

Viewing the top element without removing it.

  • Return the top element of the Stack.

Visualization of Top Operation On Stack

IsEmpty

In IsEmpty operation, we check if the stack is empty.

Checking if the stack is empty.

  • Check for the value of top in stack.

  • If (top == -1), then the stack is empty so return true .

  • Else, the stack is not empty so return false .

Visualization of IsEmpty Operation On Stack

IsFull

In IsFull operation, we check if the stack is full. This is particularly relevant for fixed-size stacks where we have a maximum capacity.

Checking if the stack has reached its maximum capacity (in fixed-size stacks).

  • Check the value of top in the stack.

  • If (top == capacity - 1), the stack is full, so return true.

  • Else, the stack isn't full, so return false.

Visualization of IsFull Operation On Stack

How is this guide?