Unit 4 Algorithm
Algorithm for Stack (using Array in C) 👇
A stack is a Last In, First Out (LIFO) data structure — the last element inserted is the first one
to be removed.
We can perform three main operations:
PUSH → insert an element
POP → remove an element
PEEK / TOP → display the top element
Algorithm: Stack using Array
1. Initialize Stack
Step 1: Start
Step 2: Declare an array stack[MAX] to hold elements
Step 3: Set top = -1 (indicates empty stack)
Step 4: Stop
2. PUSH Operation (Insert Element)
Step 1: Start
Step 2: If top == MAX - 1
Print "Stack Overflow" and stop
Step 3: Else
Increment top = top + 1
Read item to be inserted
Set stack[top] = item
Step 4: Stop
3. POP Operation (Remove Element)
Step 1: Start
Step 2: If top == -1
Print "Stack Underflow" and stop
Step 3: Else
Set item = stack[top]
Decrement top = top - 1
Print "Deleted element is item"
Step 4: Stop
4. PEEK / TOP Operation (Display Top Element)
Step 1: Start
Step 2: If top == -1
Print "Stack is empty"
Step 3: Else
Print stack[top] as top element
Step 4: Stop
5. DISPLAY Operation (Show all elements)
Step 1: Start
Step 2: If top == -1
Print "Stack is empty"
Step 3: Else
For i = top down to 0
Print stack[i]
Step 4: Stop
6. End Program
Step 1: Stop
Algorithm: Stack Using Linked List
1. Initialize Stack
Step 1: Start
Step 2: Set top = NULL (stack is empty)
Step 3: Stop
2. PUSH Operation (Insert Element)
Step 1: Start
Step 2: Create a new node
Step 3: If memory not available
Print "Stack Overflow" and stop
Step 4: Read the value item to insert
Step 5: Set newnode->data = item
Step 6: Set newnode->next = top
Step 7: Set top = newnode
Step 8: Stop
3. POP Operation (Delete Element)
Step 1: Start
Step 2: If top == NULL
Print "Stack Underflow" and stop
Step 3: Else
Set temp = top
Set item = top->data
Set top = top->next
Free memory of temp
Print "Deleted element = item"
Step 4: Stop
4. PEEK Operation (View Top Element)
Step 1: Start
Step 2: If top == NULL
Print "Stack is empty"
Step 3: Else
Print "Top element = top->data"
Step 4: Stop
5. DISPLAY Operation
Step 1: Start
Step 2: If top == NULL
Print "Stack is empty"
Step 3: Else
Set ptr = top
While ptr != NULL
Print ptr->data
Set ptr = ptr->next
Step 4: Stop