Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
29 views38 pages

FDS Answer Bank 11-20

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views38 pages

FDS Answer Bank 11-20

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

11] Double Ended Queue (Deque) Using an Array

A Double Ended Queue (Deque) is a data structure that allows insertion and deletion of elements
from both ends (front and rear). Here, we’ll implement a deque using a circular array.

Basic Operations

Insert at Front

Insert at Rear

Delete from Front

Delete from Rear

Check if Empty

Check if Full

Pseudocode for Deque Operations

Initialization

function initializeDeque(size):

deque = array of size

front = -1

rear = 0

capacity = size

Insert at Front

function insertFront(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty deque

front = 0

rear = 0

else if (front == 0):

front = capacity - 1

else:

front = front - 1
deque[front] = value

Insert at Rear

function insertRear(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty deque

front = 0

rear = 0

else if (rear == capacity - 1):

rear = 0

else:

rear = rear + 1

deque[rear] = value

Delete from Front

function deleteFront():

if (isEmpty()):

print("Underflow")

return

if (front == rear): // Only one element

front = -1

rear = -1

else if (front == capacity - 1):

front = 0

else:

front = front + 1

Delete from Rear

function deleteRear():
if (isEmpty()):

print("Underflow")

return

if (front == rear): // Only one element

front = -1

rear = -1

else if (rear == 0):

rear = capacity - 1

else:

rear = rear - 1

Check if Empty

function isEmpty():

return (front == -1)

Check if Full

function isFull():

return ((front == 0 and rear == capacity - 1) or (front == rear + 1))

Example Implementation in Python

Here’s how you might implement these operations in Python:

Python

class Deque:

def __init__(self, size):

self.deque = [None] * size

self.front = -1

self.rear = 0

self.size = size
def isFull(self):

return (self.front == 0 and self.rear == self.size - 1) or (self.front == self.rear + 1)

def isEmpty(self):

return self.front == -1

def insertFront(self, value):

if self.isFull():

print("Overflow")

return

if self.front == -1: # Empty deque

self.front = 0

self.rear = 0

elif self.front == 0:

self.front = self.size - 1

else:

self.front -= 1

self.deque[self.front] = value

def insertRear(self, value):

if self.isFull():

print("Overflow")

return

if self.front == -1: # Empty deque

self.front = 0

self.rear = 0

elif self.rear == self.size - 1:

self.rear = 0

else:

self.rear += 1

self.deque[self.rear] = value
def deleteFront(self):

if self.isEmpty():

print("Underflow")

return

if self.front == self.rear: # Only one element

self.front = -1

self.rear = -1

elif self.front == self.size - 1:

self.front = 0

else:

self.front += 1

def deleteRear(self):

if self.isEmpty():

print("Underflow")

return

if self.front == self.rear: # Only one element

self.front = -1

self.rear = -1

elif self.rear == 0:

self.rear = self.size - 1

else:

self.rear -= 1

# Example usage:

dq = Deque(5)

dq.insertRear(10)

dq.insertFront(20)

dq.insertRear(30)

dq.deleteFront()
dq.deleteRear()

12] Quick Sort Algorithm

Quick Sort is a highly efficient sorting algorithm based on the divide-and-conquer principle. It works
by selecting a ‘pivot’ element from the array and partitioning the other elements into two sub-
arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then
sorted recursively.

Pseudocode for Quick Sort

function quickSort(arr, low, high):

if low < high:

pivotIndex = partition(arr, low, high)

quickSort(arr, low, pivotIndex - 1)

quickSort(arr, pivotIndex + 1, high)

function partition(arr, low, high):

pivot = arr[high]

i = low - 1

for j from low to high - 1:

if arr[j] <= pivot:

i=i+1

swap arr[i] with arr[j]

swap arr[i + 1] with arr[high]

return i + 1

Example: Sorting the Array {4, 7, 11, 3, 4, 66, 78, 83, 12}

Let’s go through the steps of sorting this array using Quick Sort:

1. Initial Array: {4, 7, 11, 3, 4, 66, 78, 83, 12}

Pass 1:

• Pivot: 12

• Partition: {4, 7, 11, 3, 4, 12, 78, 83, 66}

• Pivot Index: 5

Recursive Calls:

• quickSort(arr, 0, 4)

• quickSort(arr, 6, 8)
Pass 2 (Left Sub-array):

• Pivot: 4

• Partition: {3, 4, 11, 7, 4, 12, 78, 83, 66}

• Pivot Index: 1

Recursive Calls:

• quickSort(arr, 0, 0) (Base case, no action)

• quickSort(arr, 2, 4)

Pass 3 (Left Sub-array):

• Pivot: 4

• Partition: {3, 4, 4, 7, 11, 12, 78, 83, 66}

• Pivot Index: 2

Recursive Calls:

• quickSort(arr, 2, 1) (Base case, no action)

• quickSort(arr, 3, 4)

Pass 4 (Left Sub-array):

• Pivot: 11

• Partition: {3, 4, 4, 7, 11, 12, 78, 83, 66}

• Pivot Index: 4

Recursive Calls:

• quickSort(arr, 3, 3) (Base case, no action)

• quickSort(arr, 5, 4) (Base case, no action)

Pass 5 (Right Sub-array):

• Pivot: 66

• Partition: {3, 4, 4, 7, 11, 12, 66, 83, 78}

• Pivot Index: 6

Recursive Calls:

• quickSort(arr, 6, 5) (Base case, no action)

• quickSort(arr, 7, 8)

Pass 6 (Right Sub-array):

• Pivot: 78

• Partition: {3, 4, 4, 7, 11, 12, 66, 78, 83}


• Pivot Index: 7

Recursive Calls:

• quickSort(arr, 7, 6) (Base case, no action)

• quickSort(arr, 8, 8) (Base case, no action)

Final Sorted Array: {3, 4, 4, 7, 11, 12, 66, 78, 83}

Time and Space Complexity

• Time Complexity:

o Best Case: (O(n \log n))

o Average Case: (O(n \log n))

o Worst Case: (O(n^2)) (occurs when the smallest or largest element is always chosen
as the pivot)

• Space Complexity: (O(\log n)) due to the recursive stack space.

Quick Sort is generally faster in practice compared to other (O(n \log n)) algorithms like Merge Sort
and Heap Sort, especially for large datasets. However, its performance can degrade to (O(n^2)) if the
pivot selection is poor.

13] Rules to Convert Prefix Expression to Infix Expression Using Stack

To convert a prefix expression to an infix expression using a stack, follow these steps:

Initialize an empty stack.

Scan the prefix expression from right to left.

For each character:

If the character is an operand, push it onto the stack.

If the character is an operator, pop two operands from the stack, combine them into a new string
with the operator in between, and push this new string back onto the stack.

The final element in the stack will be the infix expression.

Example Conversion

Given prefix expression: +a/bc-de

Step-by-Step Conversion:

Initial Stack: []

Read ‘e’: Push to stack.

Stack: [‘e’]
Read ‘d’: Push to stack.

Stack: [‘e’, ‘d’]

Read ‘-’: Pop ‘d’ and ‘e’, combine to form ‘(d - e)’, push back.

Stack: [‘(d - e)’]

Read ‘c’: Push to stack.

Stack: [‘(d - e)’, ‘c’]

Read ‘b’: Push to stack.

Stack: [‘(d - e)’, ‘c’, ‘b’]

Read ‘/’: Pop ‘b’ and ‘c’, combine to form ‘(b / c)’, push back.

Stack: [‘(d - e)’, ‘(b / c)’]

Read ‘a’: Push to stack.

Stack: [‘(d - e)’, ‘(b / c)’, ‘a’]

Read ‘+’: Pop ‘a’ and ‘(b / c)’, combine to form ‘(a + (b / c))’, push back.

Stack: [‘(d - e)’, ‘(a + (b / c))’]

Final Step: Combine the remaining elements in the stack with the operator ‘-’.

Result: ((a + (b / c)) - (d - e))

Final Infix Expression

The infix expression for the given prefix expression +a/bc-de is:

((a + (b / c)) - (d - e))

This step-by-step process ensures that the operators are correctly placed between their operands,
respecting the order of operations.

14] Applications of Stack

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. Here are some
common applications of stacks with examples:

1. Function Call Management:

o Example: When a function calls another function, the current function’s state (local
variables, return address) is pushed onto the stack. When the called function
completes, the state is popped from the stack to resume execution.

o Use Case: Recursive function calls.

2. Expression Evaluation and Conversion:


o Example: Converting infix expressions (e.g., a + b) to postfix (e.g., ab+) or prefix
(e.g., +ab) using stacks.

o Use Case: Compilers use stacks to evaluate expressions and generate machine code.

3. Backtracking:

o Example: Solving maze problems where you need to backtrack to the previous
position if a dead end is reached.

o Use Case: Depth-first search (DFS) in graph algorithms.

4. Undo Mechanism in Text Editors:

o Example: Each action (typing, deleting) is pushed onto a stack. To undo an action,
the last action is popped from the stack and reversed.

o Use Case: Text editors like Microsoft Word.

5. Parenthesis Checking:

o Example: Checking for balanced parentheses in an expression (e.g., ((a+b)*c)).

o Use Case: Syntax checking in compilers.

6. Memory Management:

o Example: Managing memory allocation and deallocation using stack frames.

o Use Case: Function call stack in programming languages.

Recursion and Its Variants

Recursion is a technique where a function calls itself to solve a problem. It breaks down a problem
into smaller subproblems of the same type.

Types of Recursion

1. Direct Recursion:

o Example: A function calls itself directly.

o Code:

o void directRecursion(int n) {

o if (n > 0) {

o printf("%d ", n);

o directRecursion(n - 1);

o }

o }

2. Indirect Recursion:

o Example: A function calls another function, which in turn calls the first function.
o Code:

o void functionA(int n);

o void functionB(int n) {

o if (n > 0) {

o printf("%d ", n);

o functionA(n - 1);

o }

o }

o void functionA(int n) {

o if (n > 0) {

o printf("%d ", n);

o functionB(n - 1);

o }

o }

3. Tail Recursion:

o Example: The recursive call is the last operation in the function.

o Code:

o void tailRecursion(int n) {

o if (n > 0) {

o printf("%d ", n);

o tailRecursion(n - 1);

o }

o }

4. Non-Tail Recursion:

o Example: The recursive call is not the last operation in the function.

o Code:

o int nonTailRecursion(int n) {

o if (n == 0) return 1;

o return n * nonTailRecursion(n - 1);

o }

5. Linear Recursion:
o Example: Each function call makes a single recursive call.

o Code:

o int linearRecursion(int n) {

o if (n == 0) return 0;

o return n + linearRecursion(n - 1);

o }

6. Tree Recursion:

o Example: Each function call makes multiple recursive calls.

o Code:

o int fibonacci(int n) {

o if (n <= 1) return n;

o return fibonacci(n - 1) + fibonacci(n - 2);

o }

Example of Recursion

Factorial Calculation:

int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n - 1);

Explanation:

• Base Case: When n is 0, return 1.

• Recursive Case: Multiply n by the factorial of n-1.

Recursion is a powerful tool for solving problems that can be broken down into smaller, similar
subproblems. Understanding its variants helps in choosing the right approach for different scenarios.

15] Double Ended Queue (Deque) Using an Array

A Double Ended Queue (Deque) is a data structure that allows insertion and deletion of elements
from both ends (front and rear). Here’s how you can implement a deque using an array in C++ and
perform the operations to create and display the deque.

Pseudocode for Deque Operations

Initialization

function initializeDeque(size):

deque = array of size


front = -1

rear = 0

capacity = size

Insert at Front

function insertFront(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty deque

front = 0

rear = 0

else if (front == 0):

front = capacity - 1

else:

front = front - 1

deque[front] = value

Insert at Rear

function insertRear(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty deque

front = 0

rear = 0

else if (rear == capacity - 1):

rear = 0

else:

rear = rear + 1

deque[rear] = value

Delete from Front

function deleteFront():
if (isEmpty()):

print("Underflow")

return

if (front == rear): // Only one element

front = -1

rear = -1

else if (front == capacity - 1):

front = 0

else:

front = front + 1

Delete from Rear

function deleteRear():

if (isEmpty()):

print("Underflow")

return

if (front == rear): // Only one element

front = -1

rear = -1

else if (rear == 0):

rear = capacity - 1

else:

rear = rear - 1

Check if Empty

function isEmpty():

return (front == -1)

Check if Full

function isFull():

return ((front == 0 and rear == capacity - 1) or (front == rear + 1))

Display Deque

function displayDeque():

if (isEmpty()):
print("Deque is empty")

return

index = front

while (index != rear):

print(deque[index])

index = (index + 1) % capacity

print(deque[rear])

Example Implementation in C++

Here’s how you might implement these operations in C++:

#include <iostream>

using namespace std;

class Deque {

private:

int* deque;

int front;

int rear;

int size;

public:

Deque(int size) {

this->size = size;

deque = new int[size];

front = -1;

rear = 0;

bool isFull() {

return (front == 0 && rear == size - 1) || (front == rear + 1);

}
bool isEmpty() {

return front == -1;

void insertFront(int value) {

if (isFull()) {

cout << "Overflow" << endl;

return;

if (front == -1) {

front = 0;

rear = 0;

} else if (front == 0) {

front = size - 1;

} else {

front = front - 1;

deque[front] = value;

void insertRear(int value) {

if (isFull()) {

cout << "Overflow" << endl;

return;

if (front == -1) {

front = 0;

rear = 0;

} else if (rear == size - 1) {

rear = 0;

} else {
rear = rear + 1;

deque[rear] = value;

void deleteFront() {

if (isEmpty()) {

cout << "Underflow" << endl;

return;

if (front == rear) {

front = -1;

rear = -1;

} else if (front == size - 1) {

front = 0;

} else {

front = front + 1;

void deleteRear() {

if (isEmpty()) {

cout << "Underflow" << endl;

return;

if (front == rear) {

front = -1;

rear = -1;

} else if (rear == 0) {

rear = size - 1;

} else {
rear = rear - 1;

void displayDeque() {

if (isEmpty()) {

cout << "Deque is empty" << endl;

return;

int index = front;

while (index != rear) {

cout << deque[index] << " ";

index = (index + 1) % size;

cout << deque[rear] << endl;

};

int main() {

Deque dq(5);

dq.insertRear(10);

dq.insertFront(20);

dq.insertRear(30);

dq.displayDeque(); // Output: 20 10 30

dq.deleteFront();

dq.displayDeque(); // Output: 10 30

dq.deleteRear();

dq.displayDeque(); // Output: 10

return 0;

}
This code defines a Deque class with methods to insert and delete elements from both ends, and to
check if the deque is full or empty. The displayDeque method prints the elements in the deque.
The main function demonstrates basic operations on the deque.

16] Queue as an Abstract Data Type (ADT)

A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. This means that
the first element added to the queue will be the first one to be removed. It has two primary
operations:

1. Enqueue: Add an element to the rear of the queue.

2. Dequeue: Remove an element from the front of the queue.

Basic Operations of a Queue

1. Enqueue: Insert an element at the rear end.

2. Dequeue: Remove an element from the front end.

3. IsEmpty: Check if the queue is empty.

4. IsFull: Check if the queue is full (for bounded queues).

5. Peek/Front: Get the front element without removing it.

Pseudocode for Queue Operations

Initialization

function initializeQueue(size):

queue = array of size

front = -1

rear = -1

capacity = size

Enqueue

function enqueue(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty queue

front = 0

rear = (rear + 1) % capacity

queue[rear] = value

Dequeue
function dequeue():

if (isEmpty()):

print("Underflow")

return

value = queue[front]

if (front == rear): // Only one element

front = -1

rear = -1

else:

front = (front + 1) % capacity

return value

IsEmpty

function isEmpty():

return (front == -1)

IsFull

function isFull():

return ((rear + 1) % capacity == front)

Peek/Front

function peek():

if (isEmpty()):

print("Queue is empty")

return

return queue[front]

Example Implementation in C++

Here’s how you might implement these operations in C++:

#include <iostream>

using namespace std;

class Queue {

private:

int* queue;
int front;

int rear;

int size;

int capacity;

public:

Queue(int capacity) {

this->capacity = capacity;

queue = new int[capacity];

front = -1;

rear = -1;

size = 0;

bool isFull() {

return size == capacity;

bool isEmpty() {

return size == 0;

void enqueue(int value) {

if (isFull()) {

cout << "Overflow" << endl;

return;

if (front == -1) {

front = 0;

rear = (rear + 1) % capacity;


queue[rear] = value;

size++;

void dequeue() {

if (isEmpty()) {

cout << "Underflow" << endl;

return;

if (front == rear) {

front = -1;

rear = -1;

} else {

front = (front + 1) % capacity;

size--;

int peek() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return -1;

return queue[front];

void displayQueue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

}
int i = front;

while (i != rear) {

cout << queue[i] << " ";

i = (i + 1) % capacity;

cout << queue[rear] << endl;

};

int main() {

Queue q(5);

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.displayQueue(); // Output: 10 20 30

q.dequeue();

q.displayQueue(); // Output: 20 30

cout << "Front element: " << q.peek() << endl; // Output: 20

return 0;

This code defines a Queue class with methods to enqueue, dequeue, check if the queue is empty or
full, peek at the front element, and display the queue. The main function demonstrates basic
operations on the queue.

17] Circular Queue Using an Array

A Circular Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle but
connects the last position back to the first position to make a circle. This helps in efficiently utilizing
the space by reusing the empty slots created by dequeuing elements.

Basic Operations of a Circular Queue

1. Enqueue: Add an element to the rear of the queue.

2. Dequeue: Remove an element from the front of the queue.

3. IsEmpty: Check if the queue is empty.

4. IsFull: Check if the queue is full.


5. Peek/Front: Get the front element without removing it.

Pseudocode for Circular Queue Operations

Initialization

function initializeQueue(size):

queue = array of size

front = -1

rear = -1

capacity = size

Enqueue

function enqueue(value):

if (isFull()):

print("Overflow")

return

if (front == -1): // Empty queue

front = 0

rear = (rear + 1) % capacity

queue[rear] = value

Dequeue

function dequeue():

if (isEmpty()):

print("Underflow")

return

value = queue[front]

if (front == rear): // Only one element

front = -1

rear = -1

else:

front = (front + 1) % capacity

return value

IsEmpty

function isEmpty():
return (front == -1)

IsFull

function isFull():

return ((rear + 1) % capacity == front)

Peek/Front

function peek():

if (isEmpty()):

print("Queue is empty")

return

return queue[front]

Example Implementation in C++

Here’s how you might implement these operations in C++:

#include <iostream>

using namespace std;

class CircularQueue {

private:

int* queue;

int front;

int rear;

int size;

int capacity;

public:

CircularQueue(int capacity) {

this->capacity = capacity;

queue = new int[capacity];

front = -1;

rear = -1;

size = 0;

}
bool isFull() {

return (rear + 1) % capacity == front;

bool isEmpty() {

return front == -1;

void enqueue(int value) {

if (isFull()) {

cout << "Overflow" << endl;

return;

if (front == -1) {

front = 0;

rear = (rear + 1) % capacity;

queue[rear] = value;

size++;

void dequeue() {

if (isEmpty()) {

cout << "Underflow" << endl;

return;

if (front == rear) {

front = -1;

rear = -1;

} else {
front = (front + 1) % capacity;

size--;

int peek() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return -1;

return queue[front];

void displayQueue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

int i = front;

while (i != rear) {

cout << queue[i] << " ";

i = (i + 1) % capacity;

cout << queue[rear] << endl;

};

int main() {

CircularQueue cq(5);

cq.enqueue(10);

cq.enqueue(20);
cq.enqueue(30);

cq.displayQueue(); // Output: 10 20 30

cq.dequeue();

cq.displayQueue(); // Output: 20 30

cout << "Front element: " << cq.peek() << endl; // Output: 20

return 0;

This code defines a CircularQueue class with methods to enqueue, dequeue, check if the queue is
empty or full, peek at the front element, and display the queue. The main function demonstrates
basic operations on the circular queue.

18] Priority Queue

A Priority Queue is a special type of queue in which each element is associated with a priority.
Elements are served based on their priority rather than their order in the queue. The element with
the highest priority is served before the elements with lower priority.

Types of Priority Queue

1. Min Priority Queue:

o In a Min Priority Queue, the element with the smallest priority value is given the
highest priority.

o Example: Consider a hospital emergency room where patients with the most critical
conditions are treated first. Here, the severity of the condition is the priority, and
lower values (more critical) are served first.

2. Max Priority Queue:

o In a Max Priority Queue, the element with the highest priority value is given the
highest priority.

o Example: Consider a task scheduling system where tasks with the highest
importance are executed first. Here, higher priority values (more important tasks)
are served first.

Example of Priority Queue Operations

Min Priority Queue Example

Let’s consider a Min Priority Queue with the following elements and their priorities:

Table

Element Priority

Task A 3
Element Priority

Task B 1

Task C 2

• Enqueue: Insert elements into the queue.

o After inserting Task A, Task B, and Task C, the queue looks like this: [Task B, Task C,
Task A] (sorted by priority).

• Dequeue: Remove the element with the highest priority (smallest value).

o Dequeue operation will remove Task B first, followed by Task C, and then Task A.

Max Priority Queue Example

Let’s consider a Max Priority Queue with the following elements and their priorities:

Table

Element Priority

Task X 5

Task Y 9

Task Z 7

• Enqueue: Insert elements into the queue.

o After inserting Task X, Task Y, and Task Z, the queue looks like this: [Task Y, Task Z,
Task X] (sorted by priority).

• Dequeue: Remove the element with the highest priority (largest value).

o Dequeue operation will remove Task Y first, followed by Task Z, and then Task X.

Implementation of Priority Queue

Priority queues can be implemented using various data structures such as arrays, linked lists, heaps,
or binary search trees. The most efficient implementation is typically done using a heap.

Pseudocode for Priority Queue Using a Min-Heap

class MinHeap:

function insert(value):

add value to the end of the heap

heapifyUp()
function heapifyUp():

index = last element index

while index > 0 and parent(index) > heap[index]:

swap parent(index) with heap[index]

index = parent index

function removeMin():

if heap is empty:

return "Underflow"

min = heap[0]

heap[0] = last element

remove last element

heapifyDown()

return min

function heapifyDown():

index = 0

while has left child(index):

smallerChildIndex = left child index

if has right child(index) and right child(index) < left child(index):

smallerChildIndex = right child index

if heap[index] < heap[smallerChildIndex]:

break

else:

swap heap[index] with heap[smallerChildIndex]

index = smallerChildIndex

This pseudocode outlines the basic operations for a Min-Heap, which can be used to implement a
Min Priority Queue. The insert function adds a new element while maintaining the heap property,
and the removeMin function removes the element with the highest priority (smallest value).

19] Queue Definition


A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. This means that
the first element added to the queue will be the first one to be removed. It is commonly used in
scenarios where order needs to be preserved, such as in scheduling tasks, managing requests in a
server, or handling processes in an operating system.

Queue Implementation Using a Linked List

When a queue is implemented using a linked list, it consists of nodes where each node contains two
parts:

1. Data: The value stored in the node.

2. Next: A pointer to the next node in the sequence.

The queue maintains two pointers:

• Front: Points to the first node in the queue.

• Rear: Points to the last node in the queue.

Basic Operations

1. Enqueue (Insertion): Adds an element to the end of the queue.

2. Dequeue (Deletion): Removes an element from the front of the queue.

3. IsEmpty: Checks if the queue is empty.

4. IsFull: Checks if the queue is full (not typically applicable for linked list implementation
unless memory is exhausted).

Conditions for Queue Empty and Queue Full

Queue Empty Condition

A queue is considered empty when there are no elements in it. For a linked list implementation, this
condition is met when the front pointer is NULL.

Pseudocode for IsEmpty:

function isEmpty():

return (front == NULL)

Queue Full Condition

In a linked list implementation, the queue is generally not considered full unless the system runs out
of memory to allocate new nodes. However, if we impose a size limit, the queue can be considered
full when the number of elements reaches this limit.

Pseudocode for IsFull:

function isFull():

node = new Node()

if (node == NULL):

return true
else:

delete node

return false

Example Implementation in C++

Here’s how you might implement these operations in C++:

#include <iostream>

using namespace std;

class Node {

public:

int data;

Node* next;

};

class Queue {

private:

Node* front;

Node* rear;

public:

Queue() {

front = NULL;

rear = NULL;

bool isEmpty() {

return (front == NULL);

bool isFull() {

Node* temp = new Node();


if (temp == NULL) {

return true;

} else {

delete temp;

return false;

void enqueue(int value) {

Node* temp = new Node();

if (temp == NULL) {

cout << "Queue is full" << endl;

return;

temp->data = value;

temp->next = NULL;

if (front == NULL) {

front = rear = temp;

} else {

rear->next = temp;

rear = temp;

void dequeue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

Node* temp = front;

front = front->next;
if (front == NULL) {

rear = NULL;

delete temp;

void displayQueue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

Node* temp = front;

while (temp != NULL) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

};

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.displayQueue(); // Output: 10 20 30

q.dequeue();

q.displayQueue(); // Output: 20 30

return 0;

}
This code defines a Queue class with methods to enqueue, dequeue, check if the queue is empty or
full, and display the queue. The main function demonstrates basic operations on the queue.

20] Applications of Queue

Queues are widely used in various fields due to their ability to manage data in a First-In-First-Out
(FIFO) manner. Here are some common applications of queues, each elaborated with a suitable
example:

CPU Scheduling:

Example: In operating systems, processes are scheduled using queues. The ready queue holds all
processes that are ready to execute and waiting for CPU time. The CPU scheduler selects the process
at the front of the queue for execution.

Explanation: This ensures that processes are executed in the order they arrive, providing fair CPU
time to all processes.

Printer Spooling:

Example: When multiple print jobs are sent to a printer, they are stored in a queue. The printer
processes each job in the order it was received.

Explanation: This prevents conflicts and ensures that print jobs are handled sequentially, avoiding
any job being skipped or delayed unnecessarily.

Handling Website Traffic:

Example: Web servers use queues to manage incoming HTTP requests. Each request is queued and
processed in the order it arrives.

Explanation: This helps in managing high traffic efficiently, ensuring that each request is handled in a
timely manner without overloading the server.

Call Center Management:

Example: In call centers, incoming calls are placed in a queue. Calls are answered in the order they
are received.

Explanation: This ensures that customers are served on a first-come, first-served basis, improving
customer satisfaction and service efficiency.

Breadth-First Search (BFS) in Graphs:

Example: BFS algorithm uses a queue to explore nodes level by level. Starting from a source node, it
visits all its neighbors before moving to the next level.

Explanation: This is useful in finding the shortest path in unweighted graphs and in scenarios like
social network analysis, where connections are explored level by level.

Task Scheduling:

Example: In real-time systems, tasks are scheduled using queues. Tasks are added to the queue
based on their arrival time and priority.
Explanation: This ensures that tasks are executed in a timely manner, respecting their priority and
arrival order, which is crucial for maintaining system performance and reliability.

Network Packet Management:

Example: Routers use queues to manage network packets. Incoming packets are queued and
processed in the order they arrive.

Explanation: This helps in managing network traffic efficiently, ensuring that packets are transmitted
without loss or delay.

Simulation Systems:

Example: In simulation systems, events are managed using queues. Events are queued and processed
in the order they are scheduled to occur.

Explanation: This allows for accurate simulation of real-world processes, such as traffic flow,
manufacturing processes, and customer service systems.

Example Code for Queue Implementation

Here’s a simple implementation of a queue using a linked list in C++:

#include <iostream>

using namespace std;

class Node {

public:

int data;

Node* next;

};

class Queue {

private:

Node* front;

Node* rear;

public:

Queue() {

front = NULL;

rear = NULL;
}

bool isEmpty() {

return (front == NULL);

void enqueue(int value) {

Node* temp = new Node();

temp->data = value;

temp->next = NULL;

if (rear == NULL) {

front = rear = temp;

} else {

rear->next = temp;

rear = temp;

void dequeue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

Node* temp = front;

front = front->next;

if (front == NULL) {

rear = NULL;

delete temp;

}
void displayQueue() {

if (isEmpty()) {

cout << "Queue is empty" << endl;

return;

Node* temp = front;

while (temp != NULL) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

};

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

q.displayQueue(); // Output: 10 20 30

q.dequeue();

q.displayQueue(); // Output: 20 30

return 0;

This code demonstrates a basic queue implementation using a linked list, which can be used in
various applications as described above.

You might also like