Module 3 Stacks and Queue
Module 3 Stacks and Queue
Basic Structure
Top [30]
[20]
[10]
● Here, 30 is the top element
● Stack grows upward
Working Example
1
Step-by-step:
Push(10) [10]
Peek() 20
Characteristics of Stack
● Follows LIFO order
● Insertion & deletion happen only at one end (top)
● Simple and efficient structure
● Can be implemented using:
o Arrays
o Linked Lists
Applications of Stack
● Function calls (recursion)
● Expression evaluation (infix, postfix)
● Undo/Redo operations
● Parenthesis checking
● Backtracking (e.g., maze solving)
Advantages
Easy to implement
Disadvantages
Limited size (array implementation)
2
No direct access to middle elements
Structure
Index: 0 1 2 3 4
top
Basic Operations
Push Operation
● Add element at top + 1
top = top + 1
stack[top] = value
Pop Operation
● Remove element from top
value = stack[top]
3
top = top - 1
Peek Operation
return stack[top]
Conditions
● Overflow when top == size - 1
● Underflow when top == -1
Advantages
Simple to implement
Disadvantages
Fixed size (cannot grow dynamically)
Wastage of memory
4
Structure
Top [30 | • ] [20 | • ] [10 | NULL]
Basic Operations
Push Operation
Create new node
new->data = value
new->next = top
top = new
Pop Operation
temp = top
top = top->next
delete temp
Peek Operation
return top->data
Conditions
● Overflow only if memory is full
● Underflow when top == NULL
Advantages
Dynamic size (grows/shrinks)
5
No memory wastage
Disadvantages
Extra memory for pointers
Slightly complex
Key Differences
Array
Feature Linked Stack
Stack
Size Fixed Dynamic
Contiguo
Memory Non-contiguous
us
When Rare (memory
Overflow
full issue)
Implementati
Easy Moderate
on
Conclusion
● Use array when size is known
● Use linked list when size is dynamic
1. Definition
6
Polish Notation (Prefix Notation) is a form of writing expressions where the operator
comes before the operands.
General Form:
Operator Operand1 Operand2
Example:
+AB
This means:
A+B
2. Example Expressions
Infix Prefix
Expression (Polish)
A+B +AB
A−B -AB
A×B *AB
A/B /AB
(A + B) × C *+ABC
A + (B × C) +A*BC
7
Example
Evaluate:
+9*23
Step-by-step:
St Sym Sta
Action
ep bol ck
1 3 Push 3
2 2 Push 2,3
2×3=6
3 * 6
push
4 9 Push 9,6
5 + 9+6=15 15
Result = 15
8
Postfix (Reverse
Polish) AB+ After operands
Summary:
Polish Notation is a prefix form of writing expressions where operators appear before
operands. It removes the need for parentheses and is efficiently evaluated using a
stack data structure.
A+B*C
(A + B) * C
3. Operator Precedence
Operat Preceden
or ce
() Highest
^ High
*/ Medium
+- Low
9
3. If the symbol is an operand, add it to the postfix expression
4. If the symbol is ( push it to the stack
5. If the symbol is ), pop from stack until ( appears
6. If the symbol is an operator
o Pop operators from stack with greater or equal precedence
o Then push the current operator
7. After scanning the expression, pop remaining operators from stack
5. Example Conversion
Convert:
A+B*C
Symb Sta Post
Action
ol ck fix
A Add to output A
+ Push + A
B Add to output + AB
Push (higher
* +* AB
precedence)
C Add to output +* ABC
ABC
End Pop all
*+
Postfix Expression:
ABC*+
6. Another Example
Convert:
(A + B) * C
Symb Sta Post
Action
ol ck fix
( Push (
A Output ( A
+ Push (+ A
B Output (+ AB
Pop
) AB+
until (
* Push * AB+
AB+
C Output *
C
AB+
End Pop
C*
Postfix Expression
10
AB+C*
7. Applications
● Expression evaluation in stack
● Compiler design
● Syntax parsing
● Expression tree creation
● Used in calculators and interpreters
11
3. Example
Evaluate the postfix expression:
23*54*+9-
Step-by-Step Evaluation
Symb Operatio Sta
ol n ck
2 Push 2
3 Push 2,3
2×3=6
* 6
push
5 Push 6,5
6,5,
4 Push
4
6,2
* 5×4=20
0
+ 6+20=26 26
26,
9 Push
9
- 26−9=17 17
Result
17
5. Advantages
● No parentheses required
● Faster evaluation using stack
● Used in compilers and calculators
● Avoids precedence problems
12
Short Exam Definition:
1. Expression Evaluation
Stacks are used to evaluate arithmetic expressions.
Examples:
● Postfix evaluation
● Prefix evaluation
Example:
23+5*
Using stack:
2+3=5
5 * 5 = 25
3. Parenthesis Checking
Stacks are used to check whether parentheses, brackets, and braces are balanced.
Example:
Valid:
{ (A + B) * C }
Invalid:
(A + B * C
Steps:
13
● Push opening brackets into stack.
● Pop when closing brackets appear.
function1()
function2()
When functions finish, they return in reverse order.
5. Backtracking
Stacks help in solving problems where we need to go back to previous steps.
Examples:
● Maze solving
● Puzzle solving
● Depth First Search (DFS)
7. Syntax Parsing
Stacks help check syntax errors in programming languages.
14
Example:
● Missing brackets
● Incorrect expression structure
Used in compiler design.
8. Reversing Data
Stacks can reverse strings or data.
Example:
Input:
HELLO
Output using stack:
OLLEH
if(base condition)
15
return value;
else
= 5 × fact(4)
= 5 × 4 × fact(3)
= 5 × 4 × 3 × fact(2)
= 5 × 4 × 3 × 2 × fact(1)
=5×4×3×2×1
= 120
C Program Example
#include<stdio.h>
int factorial(int n)
if(n==0 || n==1)
return 1;
16
else
return n * factorial(n-1);
int main()
int n=5;
return 0;
}
Output:
Factorial = 120
fact(5)
fact(4)
fact(3)
fact(2)
fact(1)
17
Then it returns back step by step.
5. Advantages of Recursion
● Makes code simpler and shorter
● Useful for complex problems
● Used in tree and graph algorithms
6. Disadvantages
● Uses more memory
● Can be slower than iteration
● May cause stack overflow if recursion is too deep
7. Applications of Recursion
1. Factorial calculation
2. Tower of Hanoi
3. Tree traversal
4. Graph algorithms
5. Searching and sorting
6. Mathematical computations
18
● Function parameters
● Local variables
● Return address (where the function should return)
● State of the function
This group of information is called a stack frame.
fact(1) = 1
Example:
fact(4)
Step 1: Function Calls (Push)
Step Stack
Call
fact(4)
fact(4)
Call
fact(4), fact(3)
fact(3)
Call
fact(4), fact(3), fact(2)
fact(2)
Call fact(4), fact(3), fact(2),
fact(1) fact(1)
19
fact(
3×2 6
3)
fact(
4×6 24
4)
Final result:
24
5. Stack Representation
Top
-----
fact(1)
fact(2)
fact(3)
fact(4)
-----
Bottom
After the base condition, elements are popped in reverse order.
6. Advantages
● Simplifies complex problems
● Easy to implement algorithms like tree traversal and Tower of Hanoi
7. Disadvantages
● Uses more memory because of stack storage
● Can cause stack overflow if recursion depth is large
Recursive procedures are implemented using a stack (call stack). Each recursive call
creates a stack frame that stores function parameters, local variables, and return
address. When the base condition is reached, the stack frames are popped in reverse
order to return the final result.
20
Tower of Hanoi is a mathematical puzzle used to demonstrate recursion.
2. Components
● Source rod (A) – where disks are initially placed
● Auxiliary rod (B) – temporary rod
● Destination rod (C) – final rod where disks must be moved
4. Recursive Algorithm
To move n disks from Source (A) to Destination (C) using Auxiliary (B):
1. Move n−1 disks from A B using C
2. Move 1 disk from A C
3. Move n−1 disks from B C using A
Algorithm
TOH(n, source, auxiliary, destination)
if n == 1
else
5. Example (3 Disks)
21
Move 3 disks from A to C using B.
St Mov
ep e
A
1
C
A
2
B
C
3
B
A
4
C
B
5
A
B
6
C
A
7
C
Total moves = 7
7. Applications
● Understanding recursion concepts
● Algorithm design
● Used in problem-solving and programming exercises
The Tower of Hanoi is a puzzle that involves moving disks from one rod to another
using recursion while following rules that only one disk can be moved at a time and
a larger disk cannot be placed on a smaller disk.
22
Queue (Data Structure)
1. Definition
A Queue is a linear data structure that follows the FIFO principle (First In First Out).
2. Basic Operations
1. Enqueue – Insert an element into the queue
2. Dequeue – Remove an element from the queue
3. Peek / Front – Display the first element
4. isEmpty – Check if queue is empty
5. isFull – Check if queue is full
3. Example of Queue
Real-life example: Queue in a ticket counter
Person1 Person2 Person3 Person4
● Person1 enters first and leaves first.
● Person4 enters last and leaves last.
4. Queue Representation
Front 10 20 30 40 # Rear
● Insertion happens at Rear
● Deletion happens at Front
23
#define MAX 5
int queue[MAX];
if(rear == MAX-1)
printf("Queue Overflow\n");
else
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
void dequeue()
24
if(front == -1 || front > rear)
printf("Queue Underflow\n");
else
front++;
void display()
int i;
if(front == -1)
printf("Queue is empty\n");
else
int main()
25
{
enqueue(10);
enqueue(20);
enqueue(30);
display();
dequeue();
display();
return 0;
6. Sample Output
10 inserted
20 inserted
30 inserted
10 20 30
10 deleted
20 30
A queue is a linear data structure that follows the FIFO (First In First Out) principle
where insertion takes place at the rear and deletion takes place at the front.
26
A Queue is a linear data structure that follows the FIFO (First In First Out) principle.
In array representation, the queue elements are stored in a linear array, and two
variables front and rear are used to track the positions of elements.
● Front points to the first element
● Rear points to the last element
-----------------------
Queue: |10 | 20 | 30 | 40 | |
-----------------------
! !
Front Rear
● Insertion (Enqueue) happens at rear
● Deletion (Dequeue) happens at front
3. Operations on Queue
1. Enqueue (Insertion)
Steps:
1. Check if rear = MAX − 1 Queue Overflow
2. If queue is empty, set front = 0
3. Increment rear
4. Insert element at queue[rear]
2. Dequeue (Deletion)
Steps:
1. Check if front = -1 or front > rear Queue Underflow
2. Delete element at queue[front]
3. Increment front
4. Algorithm
Enqueue
27
if rear == MAX-1
else
if front == -1
front = 0
rear = rear + 1
queue[rear] = item
Dequeue
if front == -1 OR front > rear
else
item = queue[front]
front = front + 1
5. Example
Initial:
Front = -1
Rear = -1
After inserting 10, 20, 30:
Index: 0 1 2
-------------
-------------
! !
Front Rear
After deleting one element:
Queue: |10 |20 |30 |
! !
Front Rear
28
10 is removed.
6. Advantages
● Simple to implement
● Easy memory allocation
● Fast insertion and deletion
7. Disadvantages
● Memory wastage when front moves forward
● Cannot reuse empty spaces in simple queue
● Can cause false overflow
2. Structure of Node
Each node contains:
[ Data | Next ]
Example queue:
Front [10|•] [20|•] [30|NULL] # Rear
● Insertion (Enqueue) happens at rear
● Deletion (Dequeue) happens at front
29
2. Insert the data into the node.
3. If queue is empty:
o Front = Rear = new node
4. Otherwise:
o Rear next = new node
o Rear = new node
5. Algorithms
Enqueue
Create newnode
newnode->data = value
newnode->next = NULL
if front == NULL
else
rear->next = newnode
rear = newnode
Dequeue
if front == NULL
else
30
temp = front
front = front->next
delete temp
6. Example
Insert elements 10, 20, 30
After insertion:
Front 10 20 30 # Rear
After deleting one element:
Front 20 30 # Rear
Element 10 is removed.
7. Advantages
● Dynamic memory allocation
● No queue overflow (until memory is full)
● Memory is used efficiently
8. Disadvantages
● Requires extra memory for pointer
● Implementation is slightly complex compared to array
There are several types of queues depending on how elements are inserted and
removed.
31
2. Circular Queue
In a circular queue, the last position is connected back to the first position to form a
circle.
Example:
Front 10 20 30
! ∀
# # # # #
Advantages:
● Efficient use of memory
● Avoids memory wastage in linear queues
3. Priority Queue
In a priority queue, elements are removed based on priority, not only by order.
Example:
Eleme Priori
nt ty
A 1
B 3
C 2
Removal order:
A C B
Applications:
● CPU scheduling
● Task management systems
32
Summary Table
Type Insertion Deletion
Simple
Rear Front
Queue
Circular
Rear Front
Queue
Priority Based on Based on
Queue priority priority
Deque Both ends Both ends
1. Enqueue (Insertion)
Enqueue means adding an element to the queue.
Front 10 20 30 # Rear
After enqueue(40)
Front 10 20 30 40 # Rear
33
2. Dequeue (Deletion)
Dequeue means removing an element from the queue.
Front 10 20 30 40 # Rear
After dequeue
Front 20 30 40 # Rear
10 is removed.
3. Peek / Front
This operation displays the first element of the queue without removing it.
Example:
Queue: 10 20 30
Peek = 10
4. isEmpty
Checks whether the queue is empty.
Condition:
front == -1 OR front > rear
5. isFull
Checks whether the queue is full.
Condition:
rear == MAX - 1
34
Operati
Description
on
Enqueu
Insert element at rear
e
Dequeu Delete element from
e front
Peek Display first element
Check if queue is
isEmpty
empty
isFull Check if queue is full
1. CPU Scheduling
Queues are used in CPU scheduling in operating systems.
Example:
● Processes waiting for CPU execution are stored in a ready queue.
● The process that arrives first gets executed first.
Example order:
P1 P2 P3 P4
2. Printer Queue
In a computer system, print jobs are stored in a printer queue.
Example:
User1 User2 User3
The first document sent to the printer is printed first.
35
Example traversal order:
Node1 Node2 Node3 Node4
Summary
Application Description
Managing process
CPU Scheduling
execution
Printer Queue Managing print jobs
Process
Handling tasks in OS
Scheduling
BFS Algorithm Graph traversal
Handling multiple
Server Requests
requests
Real-Life
Bank, ticket counters
Queues
Data Buffering Input/output operations
36
37