Array Representation of Stacks

In this method, a stack is implemented using an array and an integer variable called TOP.

  • Array → stores stack elements

  • TOP → keeps track of the index of the top element in the stack

Initial State

TOP = -1 (stack is empty)

 

Basic Operations

1. PUSH (Insert an element)

Steps:

  1. Check if TOP == size - 1
    → If yes, Stack Overflow

  2. Increment TOP

  3. Insert the element at stack[TOP]

Algorithm:

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

 

2. POP (Remove an element)

Steps:

  1. Check if TOP == -1
    → If yes, Stack Underflow

  2. Store stack[TOP]

  3. Decrement TOP

Algorithm:

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

3. PEEK (View top element)

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

 
 

Example

Assume stack size = 5

PUSH(10) → TOP = 0
PUSH(20) → TOP = 1
PUSH(30) → TOP = 2

 

Array:

Index:  0   1   2   3   4
Stack: 10  20  30  _   _
TOP → 2

 

Now POP:

Removed element = 30
TOP → 1

 

Stack Overflow & Underflow

  • Overflow → trying to push when stack is full

  • Underflow → trying to pop when stack is empty

Advantages of Array Stack

  • Simple implementation

  • Fast access (O(1))

  • Memory-efficient for fixed-size data

Disadvantages

  • Fixed size (overflow issue)

  • Wasted space if stack is underused

You have completed 0% of the lesson
0%