Operations on a Stacks.

A stack follows the LIFO (Last In, First Out) principle. The main operations are:


1. PUSH (Insertion)

Adds an element to the top of the stack.

Steps:

  1. Check if the stack is full
    → If yes, Stack Overflow

  2. Increment Top

  3. Insert the element at stack[Top]

Algorithm:

PUSH (stack, size, item):
    if TOP == size - 1:
        print "Stack Overflow"
    else:
        TOP = TOP + 1
        stack [TOP] = item
 


2. POP (Deletion)

Removes the top element from the stack.

Steps:

  1. Check if the stack is empty
    → If yes, Stack Underflow

  2. Store stack[TOP]

  3. Decrement TOP

Algorithm:

POP(stack):
    if TOP == -1:
        print "Stack Underflow"
    else:
        item = stack[TOP]
        TOP = TOP - 1
        return item


3. PEEK / TOP

Returns the top element without removing it.

Algorithm:

PEEK(stack):
    if TOP == -1:
        print "Stack is empty"
    else:
        return stack[TOP]


4. isEmpty

Checks whether the stack has no elements.

isEmpty():
    if TOP == -1:
        return true
    else:
        return false


5. isFull

Checks whether the stack is full (array implementation).

isFull(size):
    if TOP == size - 1:
        return true
    else:
        return false


Example

Stack size = 3

PUSH(5)
PUSH(10)
PUSH(15)

Stack:

Top → 15
       10
       5

Now:

POP() → removes 15
PEEK() → returns 10

You have completed 0% of the lesson
0%