Looking for AKTU Data Structure Unit 2 Notes KCS 301? Here, you can find complete and easy-to-understand notes for Unit 2 of the AKTU Data Structures subject. These notes are prepared for B.Tech students to help them understand important concepts, prepare for semester examinations, and revise all the topics covered in the KCS 301 syllabus.
On this page, you will find unit-wise study material, important concepts, explanations, algorithms, C programs, and practical examples to support your AKTU exam preparation. Whether you are preparing for your semester examination or revising important topics, these AKTU Data Structure Notes will help you study in a simple and organized way.
Unit 2 of Data Structures focuses on Stacks, Queues, Iteration, and Recursion. It covers the Stack Abstract Data Type (ADT), basic operations such as Push and Pop, and array and linked-list implementations of stacks in C. You will also learn about applications of stacks, including prefix and postfix expressions and postfix expression evaluation.
The unit further explains iteration and recursion, including the principles of recursion, tail recursion, and techniques for removing recursion. Important problem-solving examples such as binary search, Fibonacci numbers, and Tower of Hanoi are also covered, along with the differences and trade-offs between iteration and recursion.
Additionally, you will learn about Queues and their operations, including Create, Add, Delete, Full, and Empty operations. The syllabus also covers circular queues, array and linked implementations of queues in C, Deques (Double-Ended Queues), and Priority Queues.
AKTU Data Structure UNIT 2 Syllabus
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C, Application of stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Iteration and Recursion- Principles of recursion, Tail recursion, Removal of recursion Problem solving using iteration and recursion with examples such as binary search,
Fibonacci numbers, and Hanoi towers. Tradeoffs between iteration and recursion.
Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of queues in C, Dequeue and Priority Queue.
What Is a Stack?
A Stack is a linear data structure in which insertion and deletion of elements take place only at one end, called the TOP.
A stack follows the principle of LIFO (Last In, First Out). This means that the element inserted last into the stack will be the first element removed from it.
Real-life example of Stack
Consider a stack of plates in a cafeteria.
- A new plate is placed on the top.
- A plate is removed from the top.
- The plate placed last is removed first.
This behavior is similar to the stack data structure.

A stack is a linear data structure that stores elements sequentially and allows insertion and deletion operations at one end only, known as the TOP.
A stack can be implemented using two methods:
- Using Array: A stack is implemented using an array, where elements are stored in contiguous memory locations.
- Using Linked List: A stack is implemented using a linked list, where each node stores data and a pointer to the next node.
Characteristics of Stack
- It follows the LIFO principle.
- Insertion and deletion occur at the TOP.
- It is a linear data structure.
- It can be implemented using static or dynamic memory allocation.
- It maintains a TOP pointer or index.
- Push and Pop operations generally take O(1) time in standard array-based and linked-list-based stack implementations.
Applications of Stack – Short Explanations
Here is a short explanations of application of stack. Below we have added the detailed explanations.
Stacks are used in several areas of computer science.
| Application | Description |
|---|---|
| Function Calls | Stores function execution information |
| Recursion | Maintains recursive function calls |
| Expression Evaluation | Evaluates arithmetic expressions |
| Expression Conversion | Converts infix to postfix or prefix |
| Undo Operation | Stores previous actions |
| Browser History | Maintains navigation history |
| Parentheses Matching | Checks balanced brackets |
| Backtracking | Supports maze solving and path exploration |
Primitive Stack Operations — Push, Pop and Peek
1. Push Operation
The Push operation is used to insert a new element into a stack. The element is always inserted at the top of the stack.
A stack follows the LIFO (Last In, First Out) principle. Therefore, the newly inserted element becomes the first element to be removed.
Algorithm for Push Operation (Array Implementation)
- Check whether the stack is full (
TOP == MAX - 1). - If the stack is full, display Stack Overflow.
- Otherwise, increment
TOPby 1. - Insert the new element at
STACK[TOP]. - The push operation is completed.
2. Pop Operation
The Pop operation is used to remove an element from a stack. The element is always removed from the TOP position.
A stack follows the LIFO (Last In, First Out) principle. Therefore, the last inserted element is the first element to be removed.
Algorithm for Pop Operation (Array Implementation)
- Check whether the stack is empty (
TOP == -1). - If the stack is empty, display Stack Underflow.
- Otherwise, store the element at
STACK[TOP]. - Decrement
TOPby 1. - Return or display the removed element.
3. Peek Operation
The Peek operation is used to view or retrieve the topmost element of a stack without removing it.
A stack follows the LIFO (Last In, First Out) principle. The Peek operation only displays the element at the TOP position, and the stack remains unchanged.
Algorithm for Peek Operation (Array Implementation)
- Check whether the stack is empty (
TOP == -1). - If the stack is empty, display Stack Underflow.
- Otherwise, access the element at
STACK[TOP]. - Display or return the topmost element.
- Do not modify the
TOPvariable.
Conditions Arise on Stack Operations
1. Stack Overflow
Stack Overflow occurs when we try to insert a new element into a stack that is already full.
Example:
Suppose the maximum size of a stack is 5. The stack can store only 5 elements.
TOP = 4
Here, TOP = 4 means the stack is full because the array index starts from 0.
If we try to insert another element using Push(), Stack Overflow occurs.
2. Stack Underflow
Stack Underflow occurs when we try to remove an element from a stack that is already empty.
Example:
TOP = -1
Here, TOP = -1 means the stack is empty.
If we try to remove an element using Pop(), Stack Underflow occurs because there is no element to remove.
Stack Implementation Using Array And Linked List
A stack can be implemented using two methods: Array Implementation and Linked List Implementation. Both methods follow the LIFO (Last In, First Out) principle, but they differ in memory allocation and implementation.
1. Stack Implementation Using Array
In array implementation, a stack is created using a fixed-size array. A variable called top is used to keep track of the index of the topmost element.
Initially, top = -1, which indicates that the stack is empty.
How does it work?
- Push: Inserts an element at the top of the stack.
- Pop: Removes the topmost element from the stack.
- Peek: Returns the topmost element without removing it.
- Display: Prints all elements from TOP to bottom.
- Stack Overflow: Occurs when an element is inserted into a full stack.
- Stack Underflow: Occurs when an element is removed from an empty stack.
Implementation of Stack Using Array in C
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1;
void push(int item)
{
if (top == MAX - 1)
{
printf("Stack Overflow\n");
return;
}
stack[++top] = item;
printf("%d inserted\n", item);
}
void pop()
{
if (top == -1)
{
printf("Stack Underflow\n");
return;
}
printf("Deleted element: %d\n", stack[top--]);
}
void peek()
{
if (top == -1)
{
printf("Stack is Empty\n");
return;
}
printf("Top element: %d\n", stack[top]);
}
void display()
{
if (top == -1)
{
printf("Stack is Empty\n");
return;
}
printf("Stack elements:\n");
for (int i = top; i >= 0; i--)
{
printf("%d\n", stack[i]);
}
}
int main()
{
push(10);
push(20);
push(30);
display();
peek();
pop();
display();
return 0;
}
Output
10 inserted 20 inserted 30 inserted Stack elements: 30 20 10 Top element: 30 Deleted element: 30 Stack elements: 20 10
2. Stack Implementation Using Linked List
A Stack can be implemented using a Linked List instead of an array. In this method, elements are stored in the form of dynamically allocated nodes connected through pointers.
Each node contains two parts:
- Data: Stores the value of the element.
- Next Pointer: Stores the address of the next node.
The TOP pointer points to the first node of the linked list, which represents the topmost element of the stack.
Unlike an array-based stack, a linked list stack can grow dynamically depending on the availability of memory.
Node Structure
struct Node
{
int data;
struct Node *next;
};
Implementation of Stack Using Linked List in C
The following program demonstrates Push, Pop, Peek, and Display operations using a linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *top = NULL;
// Push operation
void push(int item)
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory Allocation Failed\n");
return;
}
newNode->data = item;
newNode->next = top;
top = newNode;
printf("%d inserted\n", item);
}
// Pop operation
void pop()
{
if (top == NULL)
{
printf("Stack Underflow\n");
return;
}
struct Node *temp = top;
printf("Deleted element: %d\n", top->data);
top = top->next;
free(temp);
}
// Peek operation
void peek()
{
if (top == NULL)
{
printf("Stack is Empty\n");
return;
}
printf("Top element: %d\n", top->data);
}
// Display operation
void display()
{
if (top == NULL)
{
printf("Stack is Empty\n");
return;
}
struct Node *temp = top;
printf("Stack elements:\n");
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
}
int main()
{
push(10);
push(20);
push(30);
display();
peek();
pop();
display();
return 0;
}
Output
10 inserted
20 inserted
30 inserted
Stack elements:
30
20
10
Top element: 30
Deleted element: 30
Stack elements:
20
10
Applications of Stack – Detailed Explanations
Here we have a detailed explanations of application of stack.
1. Expression Evaluation
Stacks are used to evaluate mathematical expressions and perform arithmetic operations. They help process operators and operands in the correct order based on operator precedence and associativity.
The common types of expression notations are:
- Infix: Operators are placed between operands. Example:
A + B - Prefix: Operators are placed before operands. Example:
+ A B - Postfix: Operators are placed after operands. Example:
A B +
2. Parentheses Matching
A stack is used to verify whether parentheses in an expression are balanced.
Example of Parentheses Matching:
Expression: (A + B) * (C - D)
This expression is balanced.
Expression: (A + B * (C - D)
This expression is unbalanced.
Stacks are used to manage function calls during program execution. Whenever a function is called, its execution information is stored in a special memory area called the Call Stack.
The call stack follows the LIFO (Last In, First Out) principle. The most recently called function completes its execution first.
The call stack stores:
- Local Variables: Variables declared inside a function.
- Function Parameters: Values passed to the function.
- Return Address: The location where program execution should continue after the function finishes.
- Execution State: Information required to resume the function after another function completes.
Prefix, Infix and Postfix Expressions
Expressions in data structures are ways of representing mathematical operations using operators and operands. Based on the position of the operator relative to the operands, expressions are classified into three types: Infix, Prefix, and Postfix.
1. Infix Expression
In an infix expression, the operator is placed between the operands. It is the most commonly used expression notation in mathematics and programming languages.
Example of Infix:
A + B
Here, + is the operator and A and B are operands.
Most mathematical expressions written by humans use infix notation.
2. Prefix Expression
In a prefix expression, the operator is placed before the operands. It is also known as Polish Notation.
Example of Prefix:
+ A B
It is also known as Polish notation.
3. Postfix Expression
In a postfix expression, the operator is placed after the operands. It is also known as Reverse Polish Notation (RPN).
Example of postfix:
A B +
It is also known as Reverse Polish notation.
Comparison of Prefix, Infix and Postfix Expressions
| Infix | Prefix | Postfix |
|---|---|---|
| A + B | + A B | A B + |
| A – B | – A B | A B – |
| A * B | * A B | A B * |
| A + B * C | + A * B C | A B C * + |
| (A + B) * C | * + A B C | A B + C * |
Operator Precedence Table for Expression Evaluation
Operator Precedence refers to the priority or order in which operators are evaluated in an expression. When an expression contains multiple operators, the operator with higher precedence is evaluated first.
Operator precedence helps determine the correct order of operations in mathematical expressions and programming languages.
| Operator | Precedence | Associativity |
|---|---|---|
^ (exponentiation) | Highest | Right to Left |
*, /, % | Medium | Left to Right |
+, - | Lowest | Left to Right |
Important Note: The ^ symbol represents exponentiation in these mathematical expression-conversion examples. However, in C programming, ^ represents the bitwise XOR operator, not exponentiation. C uses a different operator-precedence hierarchy.
Infix to Postfix Conversion
Algorithm of Infix to Postfix Conversion:
- Scan the infix expression from left to right.
- If the symbol is an operand, add it to the output.
- If the symbol is an opening parenthesis, push it onto the stack.
- If the symbol is an operator, pop operators of higher precedence, and of equal precedence when the current operator is left-associative, then push the current operator.
- If the symbol is a closing parenthesis, pop until the opening parenthesis is found.
- After scanning, pop all remaining operators.
Example to Convert Infix to Postfix
A + B * C
| Symbol | Stack | Postfix |
|---|---|---|
| A | Empty | A |
| + | + | A |
| B | + | AB |
| * | +, * | AB |
| C | +, * | ABC |
| End | Empty | ABC*+ |
Final Postfix: A B C * +
Infix to Prefix Conversion
Algorithm of Infix to Prefix Conversion
- Reverse the given infix expression.
- Swap every opening parenthesis
(with a closing parenthesis)and vice versa. - Convert the modified expression into postfix notation using a stack. Adjust the equal-precedence operator handling to preserve the original associativity:
- For originally left-associative operators, do not pop operators of equal precedence.
- For originally right-associative operators, pop operators of equal precedence.
- Reverse the resulting postfix expression to obtain the final prefix expression.
Example of Infix to Prefix Conversion
Example of Infix to Prefix Conversion :
Infix Expression: (A + B) * C - D
| Symbol | Stack | Postfix |
|---|---|---|
| D | Empty | D |
| – | – | D |
| C | – | DC |
| * | -, * | DC |
| ( | -, *, ( | DC |
| B | -, *, ( | DCB |
| + | -, *, (, + | DCB |
| A | -, *, (, + | DCBA |
| ) | -, * | DCBA+ |
| End | Empty | DCBA+*- |
Reverse the postfix expression:
Final Prefix: - * + A B C D
Iteration and Recursion
1. Iteration
Iteration is a programming technique in which a set of instructions is repeatedly executed using loops until a specified condition is satisfied.
In C programming, iteration is performed using three main loop statements:
forLoop: Executes a block of code repeatedly for a specified number of iterations.whileLoop: Executes a block of code as long as the given condition is true.do-whileLoop: Executes the block of code at least once before checking the condition.
Example: Factorial Using Iteration
#include <stdio.h>
int main()
{
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("Factorial = %d", fact);
return 0;
}
2. Recursion
Recursion is a programming technique in which a function calls itself to solve a problem.
In simple words, recursion means solving a problem by breaking it into smaller and simpler problems of the same type until a stopping condition is reached.
A recursive function keeps calling itself with smaller inputs until it reaches a condition where it stops.
Important Parts of Recursion
Every recursive function mainly consists of two important parts:
1. Base Case
The base case is the condition that stops the recursive function from calling itself again.
Without a base case, the function may continue calling itself indefinitely, resulting in a stack overflow.
2. Recursive Case
The recursive case is the part where a function calls itself with a smaller or simpler input to solve the problem.
Example: Factorial Using Recursion
#include
int factorial(int n)
{
if (n < 0)
return -1;
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}
int main()
{
printf("Factorial = %d", factorial(5));
return 0;
}
Factorial is defined for non-negative integers. The function returns -1 for negative input to indicate invalid input. The example uses int, so large factorial values may also cause integer overflow.
The function calls are:
factorial(5)
5 * factorial(4)
4 * factorial(3)
3 * factorial(2)
2 * factorial(1)
1
The result is calculated during the return process:
1
2 * 1 = 2
3 * 2 = 6
4 * 6 = 24
5 * 24 = 120
Principles of Recursion
Recursion is a programming technique in which a function calls itself to solve a problem by dividing it into smaller subproblems.
Every recursive function should follow certain principles to ensure that recursion executes correctly and terminates.
1. Base Case
The Base Case is the condition that stops the recursive function from calling itself. It prevents infinite recursion.
Example:
if (n == 0)
return 1;
Here, recursion stops when n becomes 0.
2. Recursive Case
The Recursive Case is the part of the function where it calls itself with a smaller or simpler version of the original problem.
Example:
return n * factorial(n - 1);
Here, the factorial() function calls itself with n - 1 to calculate the factorial.
3. Progress Toward Base Case
Each recursive call must move closer to the base case so that recursion eventually terminates.
factorial(3)
factorial(2)
factorial(1)
factorial(0) → Base Case
Here, the value of n decreases by 1 in every recursive call until it reaches 0.
If the recursive calls do not move toward the base case, infinite recursion may occur, potentially causing stack overflow.
4. Call Stack
The Call Stack is a memory structure used to manage function calls during recursion.
Each recursive call creates a new stack frame that stores information such as local variables, parameters, and the return address.
When the base case is reached, the function calls start returning in reverse order, following the LIFO (Last In, First Out) principle.
Tail Recursion: Definition, Characteristics
Tail Recursion is a type of recursion in which the recursive function call is the last operation performed by the function. No additional computation is performed after the recursive call returns.
In tail recursion, the function directly returns the result of the recursive call.
Characteristics of Tail Recursion
- The recursive function call is the last statement executed.
- No operation is performed after the recursive call returns.
- It uses an accumulator or additional parameters to maintain intermediate results.
- It may be optimized by some compilers using Tail Call Optimization (TCO).
- Without tail-call optimization, recursive calls still require call stack memory.
Removal of Recursion (Recursion to Iteration)
Removal of recursion is the process of converting a recursive function into an iterative function using loops such as for or while. It helps reduce function-call overhead and avoids excessive use of the call stack.
Example: Factorial
Recursive approach
int factorial(int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
Iterative approach:
int factorial(int n)
{
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
return fact;
}
Explanation: Both approaches calculate the factorial of a non-negative integer. The recursive approach uses repeated function calls, whereas the iterative approach uses a loop to calculate the result.
Note: Iteration generally uses O(1) auxiliary space, while this recursive implementation uses O(n) call-stack space.
Binary Search Using Iteration and Recursion
Binary Search is a searching algorithm used to find an element in a sorted array.
It repeatedly divides the search interval into two halves.
Working Principle of Binary Search
- Find the middle element.
- Compare the middle element with the target.
- If equal, return the index.
- If the target is smaller, search the left half.
- If the target is greater, search the right half.
- Repeat until the element is found or the search interval becomes empty.
1. Binary Search Using Iteration
Binary Search Using Iteration is a searching technique used to find a particular element in a sorted array by repeatedly dividing the search interval into two halves.
#include <stdio.h>
int binarySearch(int arr[], int n, int key)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int n = 7;
int result = binarySearch(arr, n, 60);
printf("Element found at index: %d", result);
return 0;
}
2. Binary Search Using Recursion
Binary Search Using Recursion is a searching technique in which a function calls itself repeatedly to find a particular element in a sorted array by dividing the search interval into two halves.
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int key)
{
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
if (arr[mid] < key)
return binarySearch(arr, mid + 1, high, key);
return binarySearch(arr, low, mid - 1, key);
}
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int result = binarySearch(arr, 0, 6, 60);
printf("Element found at index: %d", result);
return 0;
}
Fibonacci Numbers Using Iteration and Recursion
The Fibonacci Sequence is a series of numbers in which each number is obtained by adding the previous two numbers. The sequence starts with 0 and 1.
The sequence begins:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Mathematical definition:
With the initial conditions:
1. Fibonacci Using Iteration
Fibonacci Using Iteration is a method of generating Fibonacci numbers using loops instead of recursive function calls.
In this method, two variables are used to store the previous two numbers, and the next number is calculated by adding them.
#include <stdio.h>
int main()
{
int n = 10;
int a = 0, b = 1, c;
if (n <= 0)
return 0;
printf("%d ", a);
for (int i = 1; i < n; i++)
{
printf("%d ", b);
c = a + b;
a = b;
b = c;
}
return 0;
}
2. Fibonacci Using Recursion
Fibonacci Using Recursion is a method of generating Fibonacci numbers in which a function calls itself to calculate the sum of the previous two Fibonacci numbers.
In this method, the recursive function continues calling itself until it reaches the base cases.
#include <stdio.h>
int fibonacci(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main()
{
for (int i = 0; i < 10; i++)
{
printf("%d ", fibonacci(i));
}
return 0;
}
Time and Space Complexity
- Time Complexity: O(2^n), an exponential upper bound for the simple recursive implementation.
- Space Complexity: O(n), due to the maximum recursion depth.
The recursive approach repeatedly calculates the same Fibonacci numbers, which increases execution time.
For example, fibonacci(5) calculates fibonacci(3) through multiple recursive paths.
Unlike the iterative approach, which calculates each term once, the simple recursive approach performs repeated calculations.
Therefore, the iterative approach is generally more efficient for generating Fibonacci numbers.
Iteration Vs Recursion
| Basis | Iteration | Recursion |
|---|---|---|
| Repetition | Uses loops | Uses function calls |
| Termination | Loop condition | Base case |
| Memory | Usually O(1) auxiliary space | Uses call stack |
| Execution overhead | Usually lower | Usually higher |
| Stack overflow | Not caused by loop depth alone | Possible due to deep recursion |
| Suitable examples | Factorial, traversal | Tower of Hanoi, recursive binary search |
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle consisting of three rods and a number of disks of different sizes.
The main objective is to transfer all the disks from the Source Rod to the Destination Rod using an Auxiliary Rod, following a set of rules.
It is a popular example of recursion because the problem can be divided into smaller subproblems.

Rules of Tower of Hanoi
- Only one disk can be moved at a time.
- Only the topmost disk can be moved.
- A larger disk cannot be placed on a smaller disk.
- All disks must be transferred from the source rod to the destination rod.
Recursive Solution of Tower of Hanoi
To transfer n disks from the source rod to the destination rod, the following steps are performed:
- Move the top
n-1disks from the source rod to the auxiliary rod using the destination rod. - Move the largest disk from the source rod to the destination rod.
- Move the
n-1disks from the auxiliary rod to the destination rod using the source rod.
Algorithm of Tower of Hanoi
TOH(n, source, auxiliary, destination)
1. If n == 1
Move disk from source to destination
Return
2. TOH(n-1, source, destination, auxiliary)
3. Move disk from source to destination
4. TOH(n-1, auxiliary, source, destination)
Tower of Hanoi Program in C
#include <stdio.h>
void TOH(int n, char source, char auxiliary, char destination)
{
if (n <= 0)
return;
if (n == 1)
{
printf("Move disk 1 from %c to %c\n",
source, destination);
return;
}
TOH(n - 1, source, destination, auxiliary);
printf("Move disk %d from %c to %c\n",
n, source, destination);
TOH(n - 1, auxiliary, source, destination);
}
int main()
{
int n = 3;
TOH(n, 'A', 'B', 'C');
return 0;
}
Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
The following C program uses recursion to solve the Tower of Hanoi problem.
Minimum Number of Moves
The recurrence relation is:
Queue and Its Operations
A Queue is a linear data structure in which insertion of elements takes place at one end called REAR, and deletion of elements takes place at the other end called FRONT.
A queue follows the principle of FIFO (First In, First Out). This means that the element inserted first into the queue will be the first element removed.
The element inserted first is removed first.

Real-Life Example of Queue
Consider a queue of people standing at a ticket counter.
- The first person entering the queue gets the ticket first.
- New people join at the rear.
- The person at the front leaves first.
Basic Queue Operations
| Operation | Description |
|---|---|
| Create | Initializes an empty queue |
| Enqueue | Inserts an element at the rear |
| Dequeue | Removes an element from the front |
| Front | Returns the first element |
| Rear | Returns the last element |
| IsEmpty | Checks whether queue is empty |
| IsFull | Checks whether queue is full in a bounded implementation |
Queue Representation
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. The element inserted first is the first one to be removed.
A queue can be represented using two methods:
- Array Representation: A queue is implemented using an array, where elements are stored in contiguous memory locations. Two variables,
FRONTandREAR, are used to manage deletion and insertion operations. - Linked List Representation: A queue is implemented using a linked list, where elements are stored in dynamically allocated nodes connected through pointers. The
FRONTpointer points to the first node, and theREARpointer points to the last node.
Two variables are commonly used:
In queue representation, two variable FRONT and REAR generally used.
- FRONT — points to the first element in the queue.
- REAR — points to the last element in the queue.
Queue Operations
1. Queue Initialization
In an array-based queue, two variables named front and rear are used to keep track of the first and last elements of the queue.
int queue[MAX];
int front = -1;
int rear = -1;
Here:
front = -1
rear = -1
indicates that the queue is empty.
2. Enqueue Operation
Enqueue is the operation of inserting a new element into the queue. The new element is always inserted at the REAR end.
Before inserting an element, the queue is checked for overflow. If the queue is full, insertion is not possible.
Algorithm
ENQUEUE(QUEUE, ITEM)
1. If REAR == MAX - 1
Print "Queue Overflow"
Return
2. If FRONT == -1
FRONT = 0
3. REAR = REAR + 1
4. QUEUE[REAR] = ITEM
3. Dequeue Operation
Dequeue is the operation of removing an element from the queue. The element is always removed from the FRONT end.
Before deleting an element, the queue is checked for underflow. If the queue is empty, deletion is not possible.
Algorithm
DEQUEUE(QUEUE)
1. If FRONT == -1
Print "Queue Underflow"
Return
2. ITEM = QUEUE[FRONT]
3. If FRONT == REAR
FRONT = -1
REAR = -1
4. Else
FRONT = FRONT + 1
5. Return ITEM
Queue Overflow and Underflow Conditions
1. Queue Overflow
Queue Overflow occurs when we try to insert a new element into a queue that is already full.
In a simple array-based (linear) queue, when the REAR reaches the last position of the array (MAX - 1), no more elements can be inserted.
Example:
Consider a queue with a maximum capacity of 5 elements:
[10, 20, 30, 40, 50]
Now, if we try to insert 60, the queue cannot accept the new element because it is already full.
Result: Queue Overflow.
2. Queue Underflow
Queue Underflow occurs when we try to delete an element from a queue that is already empty.
When there are no elements available in the queue, the Dequeue operation cannot be performed.
Example:
Consider an empty queue:
[Empty]
Now, if we try to delete an element using the Dequeue operation, there is no element available to remove.
Result: Queue Underflow.
Circular Queue
A Circular Queue is a linear data structure in which the last position is connected back to the first position, forming a circular structure. It follows the FIFO (First In, First Out) principle.
It is also known as a Ring Buffer.
In a circular queue, when the REAR reaches the last position of the array, it can move back to the first position if an empty space is available. This allows previously occupied positions to be reused.
Unlike a linear queue, a circular queue makes efficient use of available memory by avoiding unnecessary space wastage.

What is the Need for Circular Queue?
In a linear queue, deleted positions at the beginning cannot be reused without shifting elements.
This causes memory wastage.
Circular queues overcome this problem by reusing the vacant positions.
Example of Circular Queue
Consider an array of size 5.
Initially:
[10, 20, 30, 40, 50]
After deleting 10 and 20:
[_, _, 30, 40, 50]
A linear queue may report overflow when rear reaches the final index, even though the first two positions are vacant.
A circular queue reuses these vacant positions.
Circular Queue Conditions
1. Empty Condition
The queue is empty when front is equal to -1.
front == -1
2. Full Condition
The queue is full when the next position of rear reaches front.
(rear + 1) % MAX == front
3. Rear Update
Moves the rear pointer to the next position. If it reaches the end, it moves back to index 0.
rear = (rear + 1) % MAX;
4. Front Update
Moves the front pointer to the next position. If it reaches the end, it moves back to index 0.
front = (front + 1) % MAX;
Circular Queue Enqueue Algorithm
ENQUEUE(QUEUE, ITEM)
1. If (REAR + 1) % MAX == FRONT
Print "Queue Overflow"
Return
2. If FRONT == -1
FRONT = 0
REAR = 0
3. Else
REAR = (REAR + 1) % MAX
4. QUEUE[REAR] = ITEM
Circular Queue Dequeue Algorithm
DEQUEUE(QUEUE)
1. If FRONT == -1
Print "Queue Underflow"
Return
2. ITEM = QUEUE[FRONT]
3. If FRONT == REAR
FRONT = -1
REAR = -1
4. Else
FRONT = (FRONT + 1) % MAX
5. Return ITEM
Queue Implementation Using Array and Linked List
1. Queue Implementation using Array in C
A queue can be implemented using an array by maintaining two variables:
- FRONT
- REAR
The insertion operation takes place at REAR, while deletion takes place at FRONT.
Queue Implementation using Array program in C
#include <stdio.h>
#define MAX 5
int queue[MAX];
int front = -1;
int rear = -1;
// Enqueue Operation
void enqueue(int item)
{
if ((rear + 1) % MAX == front)
{
printf("Queue Overflow\n");
return;
}
if (front == -1)
front = 0;
rear = (rear + 1) % MAX;
queue[rear] = item;
printf("%d inserted\n", item);
}
// Dequeue Operation
void dequeue()
{
if (front == -1)
{
printf("Queue Underflow\n");
return;
}
printf("Deleted element: %d\n", queue[front]);
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front + 1) % MAX;
}
}
// Display Operation
void display()
{
if (front == -1)
{
printf("Queue is Empty\n");
return;
}
printf("Queue elements: ");
int i = front;
while (1)
{
printf("%d ", queue[i]);
if (i == rear)
break;
i = (i + 1) % MAX;
}
printf("\n");
}
int main()
{
enqueue(10);
enqueue(20);
enqueue(30);
display();
dequeue();
display();
return 0;
}
Output:
10 inserted
20 inserted
30 inserted
Queue elements: 10 20 30
Deleted element: 10
Queue elements: 20 30
2. Linked List Implementation of Queue in C
Node Structure
The following structure defines a node in the linked list:
struct Node
{
int data;
struct Node *next;
};
Here:
rearpoints to the last node of the queue. A linked-list implementation does not require a predefined fixed capacity, although it is limited by the available system memory.datastores the queue element.nextstores the address of the next node.frontpoints to the first node.
Initially, both front and rear are set to NULL, indicating that the queue is empty.
C Program for Queue implementation Using Linked List
The following C program demonstrates the implementation of a queue using a linked list with Enqueue, Dequeue, and Display operations.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *front = NULL;
struct Node *rear = NULL;
// Enqueue Operation
void enqueue(int item)
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory Allocation Failed\n");
return;
}
newNode->data = item;
newNode->next = NULL;
if (rear == NULL)
{
front = rear = newNode;
}
else
{
rear->next = newNode;
rear = newNode;
}
printf("%d inserted\n", item);
}
// Dequeue Operation
void dequeue()
{
if (front == NULL)
{
printf("Queue Underflow\n");
return;
}
struct Node *temp = front;
printf("Deleted element: %d\n", front->data);
front = front->next;
if (front == NULL)
rear = NULL;
free(temp);
}
// Display Operation
void display()
{
if (front == NULL)
{
printf("Queue is Empty\n");
return;
}
struct Node *temp = front;
printf("Queue elements: ");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
enqueue(10);
enqueue(20);
enqueue(30);
display();
dequeue();
display();
return 0;
}
Enqueue Operation in a Queue Using Linked List
Enqueue is the operation of inserting a new element into a queue. In a linked list implementation, the new node is always inserted at the REAR end.
Steps:
- Create a new node using dynamic memory allocation (
malloc()). - Store the element in the data part of the new node.
- Set the next pointer of the new node to
NULL. - If the queue is empty, set both FRONT and REAR to the new node.
- Otherwise, connect the current REAR node to the new node.
- Update REAR to point to the newly inserted node.
Example of Enqueue:
Consider an empty queue. Insert the elements 10, 20, and 30.
- Initially, FRONT and REAR are
NULL. - Insert 10: Create a new node and set both FRONT and REAR to that node.
- Insert 20: Connect the next pointer of node 10 to node 20 and update REAR to node 20.
- Insert 30: Connect the next pointer of node 20 to node 30 and update REAR to node 30.
Final Queue: 10 → 20 → 30
Dequeue Operation in a Queue Using Linked List
Dequeue is the operation of removing an element from a queue. In a linked list implementation, the element is always removed from the FRONT end.
Steps:
- Check whether FRONT is
NULL. If it is, the queue is empty and Queue Underflow occurs. - Store the FRONT node temporarily in a pointer called
temp. - Move FRONT to the next node using
front = front->next. - If FRONT becomes
NULL, set REAR toNULLbecause the queue is now empty. - Free the deleted node using
free(temp).
Example of Dequeue:
Consider the following queue:
10 → 20 → 30
- Initially, FRONT points to node 10 and REAR points to node 30.
- Store the FRONT node (10) temporarily in
temp. - Move FRONT to the next node (20).
- Delete the previous FRONT node (10) using
free(temp).
Final Queue: 20 → 30
Deque — Double Ended Queue
A Deque (Double Ended Queue) is a linear data structure in which insertion and deletion operations can be performed at both ends, FRONT and REAR.
Unlike a normal queue, where insertion takes place only at the REAR and deletion takes place only at the FRONT, a deque allows elements to be inserted and deleted from either end.
Types of Deque
1. Input Restricted Deque
An Input Restricted Deque is a type of deque in which insertion is allowed only at one end (REAR), while deletion is allowed at both FRONT and REAR ends.
Example of Input Restricted Deque:
- Insert elements only at REAR.
- Delete elements from either FRONT or REAR.
2. Output Restricted Deque
An Output Restricted Deque is a type of deque in which deletion is allowed only at one end (FRONT), while insertion is allowed at both FRONT and REAR ends.
Example of Output Restricted Deque:
- Insert elements at either FRONT or REAR.
- Delete elements only from FRONT.
Operations on dequeue
| Operation | Description |
|---|---|
| InsertFront | Inserts an element at FRONT |
| InsertRear | Inserts an element at REAR |
| DeleteFront | Removes an element from FRONT |
| DeleteRear | Removes an element from REAR |
Example of Deque Operations
Consider an initially empty deque.
- InsertRear(10): Inserts 10 at the REAR.
- InsertRear(20): Inserts 20 at the REAR.
- InsertFront(5): Inserts 5 at the FRONT.
- DeleteRear(): Removes 20 from the REAR.
- DeleteFront(): Removes 5 from the FRONT.
Final Deque: 10
Priority Queue
A Priority Queue is a special type of queue in which each element is assigned a priority. Elements are inserted into the queue along with their priority and are removed according to their priority rather than their insertion order.
The element with the highest priority is processed first. If two elements have the same priority, they are generally processed according to the FIFO (First In, First Out) principle.
Types of Priority Queue
1. Ascending Priority Queue
An Ascending Priority Queue is a type of priority queue in which the element with the smallest priority value is removed first.
Elements are processed in ascending order of their priority values.
Example of Ascending Priority Queue:
Consider the following elements:
A(3), B(1), C(2), D(4)
Deletion order:
B → C → A → D
2. Descending Priority Queue
A Descending Priority Queue is a type of priority queue in which the element with the largest priority value is removed first.
Elements are processed in descending order of their priority values.
Example of Descending Priority Queue:
Consider the following elements:
A(3), B(1), C(2), D(4)
Deletion order:
D → A → C → B
Basic Operations of Priority Queue
| Operation | Description |
|---|---|
| Insert | Adds an element along with its priority. |
| Delete | Removes the element with the highest priority. |
| Peek | Returns the element with the highest priority without removing it. |
| IsEmpty | Checks whether the priority queue is empty. |
Important Data Structure AKTU Examination Questions – Unit 2
- Explain the Stack ADT and its primitive operations with algorithms.
- Explain the array and linked list implementation of Stack with C programs.
- Convert an infix expression into postfix and prefix expressions using a stack.
- Explain the algorithm for evaluating a postfix expression with an example.
- Explain recursion and its principles with suitable examples.
- Explain tail recursion and removal of recursion.
- Write recursive and iterative algorithms for Binary Search.
- Explain Fibonacci series using recursion and iteration.
- Explain Tower of Hanoi with its algorithm and time complexity.
- Explain Queue operations with array implementation in C.
- Explain Circular Queue with algorithms and C program.
- Explain linked list implementation of Queue.
- Explain Deque and its types.
- Explain Priority Queue and its applications.
- Compare iteration and recursion.
Explore More Resources Data Structures
| Resource | Description | Link |
|---|---|---|
| Data Structures Question Bank | Practice important questions, MCQs, and exam-oriented questions on Data Structures. | Data Structure Previous Year Questions and Answers → |
| Data Structures Previous Year Question Papers | Prepare using previous year university question papers for Data Structures. | Data Structure Previous Year Question Papers → |
Explore Other AKTU Data Structures Units
Continue your AKTU Data Structures preparation with complete unit-wise notes, explanations, diagrams, algorithms, and important questions.
| Data Structures Units | Study Notes |
|---|---|
| Unit 1-Introduction to Data Structures, Arrays and Linked Lists | Read Unit 1 Notes → |
| Unit 3-Sorting and searching | Read Unit 3 Notes → |
| Unit 4-Graphs and Graph Algorithms | Read Unit 4 Notes → |
| Unit 5-Trees and Binary Trees | Read Unit 5 Notes → |
Explore More Study Materials
Explore more AKTU B.Tech CSE notes, syllabus, and examination preparation resources on Quescol.