Algorithm


Stack Implementation (Using Array):

  1. Initialize an array stack[] to store the elements of the stack.
  2. Initialize a variable top to -1 to represent the top of the stack.
  3. Define the following operations:
    1. Push: Add an element to the stack.
      1. Check if the stack is full. If top == maxSize - 1, display an overflow error.
      2. Otherwise, increment top and set stack[top] = element.
    2. Pop: Remove the top element from the stack.
      1. Check if the stack is empty. If top == -1, display an underflow error.
      2. Otherwise, return stack[top] and decrement top.
    3. Peek: Retrieve the top element without removing it.
      1. Check if the stack is empty. If top == -1, display an error.
      2. Otherwise, return stack[top].
    4. IsEmpty: Check if the stack is empty by verifying if top == -1.
    5. IsFull: Check if the stack is full by verifying if top == maxSize - 1.

Example:

Consider a stack with a maximum size of 5. Perform the following operations:

  • Push 10, 20, 30
  • Pop an element
  • Peek the top element

The stack will contain [10, 20] after these operations, and the top element will be 20.