0% found this document useful (0 votes)
316 views129 pages

DSA - Lab Workbook

Here is the code: #include <stdio.h> #include <stdlib.h> int main() { int arr[10], i; // Initialize array with random numbers srand(time(0)); for(i=0; i<10; i++) { arr[i] = rand()%100; } // Print even elements printf("Even elements: "); for(i=0; i<10; i+=2) { printf("%d ", arr[i]); } printf("\n"); // Print odd elements printf("Odd elements: "); for(i=1; i<10; i+=

Uploaded by

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

DSA - Lab Workbook

Here is the code: #include <stdio.h> #include <stdlib.h> int main() { int arr[10], i; // Initialize array with random numbers srand(time(0)); for(i=0; i<10; i++) { arr[i] = rand()%100; } // Print even elements printf("Even elements: "); for(i=0; i<10; i+=2) { printf("%d ", arr[i]); } printf("\n"); // Print odd elements printf("Odd elements: "); for(i=1; i<10; i+=

Uploaded by

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

Data Structures

(MCL 507)

Lab Workbook

Faculty name: Student name: Sandeep Kaushal

Roll No.: 23MCA009

Semester: 1

Group: MCA

Department of Computer Science and Engineering


The NorthCap University, Gurugram- 122017, India
Session 2023-24
Data Structures- MCL507
Session – 2023-25
INDEX
S.No Experiment Date of Date of Student CO Faculty
Experiment Submission Sign Covered Sign
1 Create an array of
integer with size n.
Return the
difference between
the largest and the
smallest value
inside that array.
2 1. Write a program that
initializes an array with
ten random integers and
then prints four lines of
output, containing:
 Every
element at an
even index
 Every odd
element
 All elements
in reverse
order
Only the first
and last element
3 2 Write a program to read
numbers in an integer
array of size 5 and
display the following:
 Sum of all the
elements
 Sum of
alternate elements in
the array
 Second
highest element in
the array
Data Structures Lab Workbook (MCL507) | 1
2023--25

4 Write a program to
create a singly linked
list of n nodes and
perform:

• Insertion

o At the beginning
o At the end
o At a specific
location

• Deletion

o At the beginning
o At the end

At a specific
location

5 Write a program to
create a doubly linked
list of n nodes and
perform:

• Insertion

o At the beginning
o At the end
o At a specific
location

• Deletion

o At the beginning
o At the end

At a specific
location
Data Structures Lab Workbook (MCL507) | 2
2023--25
6 Write a program to
create a circular linked
list of n nodes and
perform:

• Insertion

o At the beginning
o At the end
o At a specific
location

• Deletion

o At the beginning
o At the end

At a specific
location

7 Write a program to
implement stack
using arrays and
linked lists.

8 Write a program to
reverse a sentence
using stack.

9 Write a program to
check for balanced
parenthesis in a
given expression.

10 Write a program to
convert infix
expression to prefix
and postfix
expression.

11
Write a program to
Data Structures Lab Workbook (MCL507) | 3
2023--25
implement Tower of
Hanoi using stacks

12 Write a program to
implement Linear
Queue using Array
and Linked Lists.

13 Write a program to
implement Circular
Queue using Array
and Linked Lists.

14 Write a program to
implement Doubly
Ended Queue using
Array and Linked
Lists.

15 Write a Program to
implement Binary
Search Tree
operations.

16 Write a program to
implement Bubble
Sort, Selection Sort,
Quick Sort, Merge
Sort and Insertion
Sort algorithm.
Data Structures Lab Workbook (MCL507) | 4
2023--25
EXPERIMENT NO. 1

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure array and its basic operations

Outcome:

The students will be able to implement and use arrays for solving various problems

Problem Statement:

Create an array of integer with size n. Return the difference between the largest and the smallest value inside
that array.

Background Study:

An Array is a data structure consisting of a collection of elements (values or variables), each identified
by at least one array index or key. An array is stored such that the position of each element can be
computed from its index tuple by a mathematical formula. The simplest type of data structure is a
linear array, also called one-dimensional array.
Data Structures Lab Workbook (MCL507) | 5
2023--25

Algorithm (Student Work Area):

1. Input the array elements.


2. Initialize small = large = arr[0]
3. Repeat for i = 2 to n
4. if(arr[i] > large)

large = arr[i]

5. if(arr[i] < small)

small = arr[i]

6. Print small and large.


7. Print Large-small(difference between largest and smallest element).

Code (Student Work Area):

#include<stdio.h>

int main()

int a[50],i,n,large,small;

printf("Enter the number of elements : ");

scanf("%d",&n);

printf("Input the array elements : ");

for(i=0;i<n;++i){
Data Structures Lab Workbook (MCL507) | 6
2023--25
scanf("%d",&a[i]);}

large=small=a[0];

for(i=1;i<n;++i)

if(a[i]>large)

large=a[i];

if(a[i]<small)

small=a[i];

printf("The smallest element is %d\n",small);

printf("The largest element is %d\n",large);

printf("difference : %d",large-small);

return 0;

Output- screenshots (students work area):

Question Bank:

1. What is Data Structure?


Data Structures Lab Workbook (MCL507) | 7
2023--25
2. Why Array is called as Linear Data Structure?

3. What type of Indexing is used in Java?

4. How to find the missing number in integer array of 1 to 100?

5. How to find the second-highest value in a numeric array?

6. How to swap the first and last elements of an array?

7. Write a Java Program to check if see if Array contains a specific value. (Linear Search)

EXPERIMENT NO. 2

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure array and its basic operations

Outcome:

The students will be able to implement and use arrays for solving various problems

Problem Statement:

1. Write a program that initializes an array with ten random integers and then prints four lines of
Data Structures Lab Workbook (MCL507) | 8
2023--25
output, containing:
 Every element at an even index
 Every odd element
 All elements in reverse order
 Only the first and last element

Background Study:

An Array is a data structure consisting of a collection of elements (values or variables), each


identified by at least one array index or key. An array is stored such that the position of each
element can be computed from its index tuple by a mathematical formula. The simplest type of data
structure is a linear array, also called one-dimensional array.

Algorithm (Student Work area):

1. Every element at an even index:

1. Initialize i=0
2. Repeat steps 3 and 4 until for i<10.
3. Inside the loop, print the element at index i.
4. Increment i +=2 to move to the next even index.
5. End of for loop

2.Algorithm for Every odd element:

6. Initialize i=1
7. Repeat steps 3 and 4 until for i<10.
8. Inside the loop, print the element at index 'i'.
9. Increment i+= 2 to move to the next odd index.
10. End of for loop.

3.Algorithm for All the elements in reverse order:

11. Initialize i=(array length - 1).


Data Structures Lab Workbook (MCL507) | 9
2023--25
12. Repeat steps 3 and 4 until for i>=0.
13. Inside the loop, print the element at index 'i'.
14. Decrement i-- to move to the previous index.
15. End of for loop.

Algorithm for Original order of elements:

16. Initialize i=0


17. Repeat steps 3 and 4 until for i<10.
18. Inside the loop, print the element at index 'i'.
19. Increment i++ to move to the next index.
20. End of for loop

Code (Student Work Area):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int random_integers[10];
int i;
// Seed the random number generator
srand(time(0));

// Initialize the array with ten random integers


for (i = 0; i < 10; i++) {
random_integers[i] = rand() % 100;
}

// Print every element at an even index (0, 2, 4, 6, 8)


printf("Every element at an even index:\n");
for (i = 0; i < 10; i += 2) {
printf("%d\t",random_integers[i]);
}
// Print every odd element (1, 3, 5, 7, 9)
printf("\nEvery odd element:\n");
for (i = 1; i < 10; i += 2) {
printf("%d\t",random_integers[i]);
}

// Print all the elements in reverse order


printf("\nAll the elements in reverse order:\n");
for (i = 9; i >= 0; i--) {
Data Structures Lab Workbook (MCL507) | 10
2023--25
printf("%d\t",random_integers[i]);
}

// Print the elements in the original order


printf("\nOriginal order of elements:\n");
for (i = 0; i < 10; i++) {
printf("%d\t", random_integers[i]);
}
return 0;
}

Output- screenshots (students work area):

Question Bank:

1. How we can segregate all 0s on left side and all 1s on right side of a given array of 0s and
1s.
2. How to reverse the array elements.
3. How to find the index of an array element
4. How to remove a specific element from an array.
5. How to insert an element (specific position) into an array.
Data Structures Lab Workbook (MCL507) | 11
2023--25

EXPERIMENT NO. 3

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure array and its basic operations

Outcome:

The students will be able to implement and use arrays for solving various problems

Problem Statement:

3 Write a program to read numbers in an integer array of size 5 and display the following:
 Sum of all the elements
Data Structures Lab Workbook (MCL507) | 12
2023--25
 Sum of alternate elements in the array
 Second highest element in the array

Background Study:

An Array is a data structure consisting of a collection of elements (values or variables), each


identified by at least one array index or key. An array is stored such that the position of each
element can be computed from its index tuple by a mathematical formula. The simplest type of data
structure is a linear array, also called one-dimensional array.

Algorithm (Student Work Area):

1.Algorithm for Sum of all elements:

1. Initialize sum= 0.
2. Repeat for i= 0 to 4.
3. Inside the loop, sum += numArray[i];.
4. Repeat steps 2 and 3 for all elements in the array.
5. End of loop
6. Print the value of 'sum'.

2.Algorithm for Sum of alternate elements in the array:

1. Initialize sumAlt= 0.
2. Repeat for i=0.
3. Inside the loop, sumAlt+= numArray[i].
4. Increment i+= 2 to move to the next alternate element.
5. Repeat steps 3 and 4 for all alternate elements in the array.
6. Print the value of 'sumAlt'

3.Algorithm for Finding the Second Highest Element in the Array:

1. Initialize max=0 and secondMax=0


2. Create a loop that iterates through the array.
3. Inside the loop, compare the current element with 'max'. If the current element is greater than
Data Structures Lab Workbook (MCL507) | 13
2023--25
'max', update 'secondMax' to the value of 'max' and 'max' to the current element.
4. If the current element is not greater than 'max' but greater than 'secondMax' and not equal to
'max', update 'secondMax' to the current element.
5. Repeat steps 3 and 4 for all elements in the array.
6. Print the value of 'secondMax'.

Code (Student Work Area):

#include <stdio.h>

int main() {
int numArray[5];
int i;
int sum = 0;
int sumAlt = 0;
int max = 0;
int secondMax = 0;
printf("Enter 5 integers:\n");
for (i = 0; i < 5; i++) {
scanf("%d", &numArray[i]);
}

// Calculate the sum of all elements


for (i = 0; i < 5; i++) {
sum += numArray[i];
}
// Calculate the sum of alternate elements
for (i = 0; i < 5; i += 2) {
sumAlt += numArray[i];
}
// Find the second highest element
for (i = 0; i < 5; i++) {
if (numArray[i] > max) {
secondMax = max;
max = numArray[i];
} else if (numArray[i] > secondMax && numArray[i] != max) {
secondMax = numArray[i];
}
}
// Display the results
printf("Sum of all elements: %d\n", sum);
printf("Sum of alternate elements: %d\n", sumAlt);
printf("Second highest element: %d\n", secondMax);
Data Structures Lab Workbook (MCL507) | 14
2023--25
return 0;
}

Output – screenshots (students work area):

Question Bank:

1. How we can count occurrence of a given number in the array and its frequency.

2. How we can print the following in 2-D integer array with each element of maximum 2 digits

a) Elements of the entered array.


b) Elements of the array after each element is multiplied by 2 if it is an odd number.

3. Given an array of integers, return the number of times that two 6's are next to each other in
the array. Also count instances where the second element is 7

4. Write a method called swapPairs() that accepts an array of integers and swaps the elements at
adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so
on. If the array has an odd length, the final element should be left unmodified. For example, the
list {10, 20, 30, 40, 50} should become {20, 10, 40, 30, 50} after a call to your method.

5. Write a method called median() that accepts an array of integers as its argument and returns
the median of the numbers in the array. The median is the number that will appear in the middle
if you arrange the elements in order.
Data Structures Lab Workbook (MCL507) | 15
2023--25

EXPERIMENT NO. 4

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Linked List and its basic operations

Outcome:
Data Structures Lab Workbook (MCL507) | 16
2023--25
The students will be able to implement and use singly linked list for solving various problems

Problem Statement:

Write a program to create a singly linked list of n nodes and perform:

• Insertion

o At the beginning
o At the end
o At a specific location

• Deletion

o At the beginning
o At the end
o At a specific location

Background Study:

Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has to
be inserted.

Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode).
Then point B.next to C −
NewNode.next −> RightNode;
It should look like this −
Data Structures Lab Workbook (MCL507) | 17
2023--25

Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;

This will put the new node in the middle of the two. The new list should look like this −

Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the new
node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.
Data Structures Lab Workbook (MCL507) | 18
2023--25

The left (previous) node of the target node now should point to the next node of the target node

LeftNode.next −> TargetNode.next;

This will remove the link that was pointing to the target node. Now, using the following code, we
will remove what the target node is pointing at.
TargetNode.next −> NULL;

We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.

Algorithm (Student Work Area):

Algorithm for Creating a Singly Linked List:

1. Create a structure with two members: data and a pointer *next.


2. Create a function 'createNode(value)' that takes an integer value as input and returns a new node
Data Structures Lab Workbook (MCL507) | 19
2023--25
with the given value and a 'NULL' next pointer.
3. Initialize a head pointer to 'NULL' to represent an empty linked list.
4. Read the number of nodes 'n' from the user.
5. For each node, perform the following:
a. Read a value from the user.
b. Create a new node with the value using the 'createNode' function.
c. Add the new node to the end of the linked list using the 'insertAtEnd' function

Algorithm for Inserting a Node at the Beginning:

1. Create function 'insertAtBeginning(head, value)' that takes the current head pointer and a value as
input.
2. Create a new node with the given value using the 'createNode' function.
3. Set the next pointer of the new node to the current head.
4. Update the head pointer to point to the new node.
5. Return the updated head pointer.

Algorithm for Inserting a Node at the End:

1. Create a function 'insertAtEnd(head, value)' that takes the current head pointer and a value as
input.
2. Create a new node with the given value using the 'createNode' function.
3. If the linked list is empty (head is NULL), set the head pointer to the new node and return it.
4. Otherwise, traverse the linked list to the last node.
5. Update the next pointer of the last node to point to the new node.
6. Return the original head pointer.

Algorithm for Inserting a Node at a Specific Location:

1. Create a function 'insertAtLocation(head, value, position)' that takes the current head pointer, a
value, and a position as input.
2. Create a new node with the given value using the 'createNode' function.
3. If the position is less than 1 or the linked list is empty, print an error message and return the
original head pointer.
4. If the position is 1, insert the new node at the beginning using the 'insertAtBeginning' function.
5. Otherwise, traverse the linked list to the node just before the desired position.
6. Update the 'next' pointers to insert the new node at the specified position.
7. Return the original head pointer.

Algorithm for Deleting a Node from the Beginning:

1. Create a function 'deleteFromBeginning(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return 'NULL'.
3. Otherwise, create a temporary pointer to the first node and update the head pointer to the second
Data Structures Lab Workbook (MCL507) | 20
2023--25
node.
4. Free the memory of the temporary pointer.
5. Return the updated head pointer.

Algorithm for Deleting a Node from the End:

1. Create a function 'deleteFromEnd(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return 'NULL'.
3. If the linked list has only one node, free its memory and set the head pointer to 'NULL'.
4. Otherwise, traverse the linked list to the node just before the last node.
5. Update the 'next' pointer of the previous node to 'NULL'.
6. Free the memory of the last node.
7. Return the updated head pointer

Algorithm for Deleting a Node from a Specific Location:

1. Create a function 'deleteFromLocation(head, position)' that takes the current head pointer and a
position as input.
2. If the position is less than 1 or the linked list is empty (head is 'NULL'), print an error message and
return the original head pointer.
3. If the position is 1, delete the first node using the 'deleteFromBeginning' function.
4. Otherwise, traverse the linked list to the node just before the desired position.
5. Update the 'next' pointers to remove the node at the specified position.
6. Free the memory of the removed node.
7. Return the original head pointer.

Code (Student Work Area):

#include <stdio.h>

#include <stdlib.h>

// Define a structure for a node in the linked list


struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the beginning of the linked list
Data Structures Lab Workbook (MCL507) | 21
2023--25
struct Node* insertAtBeginning(struct Node* head, int value) {
struct Node* newNode = createNode(value);
newNode->next = head;
return newNode;
}

// Function to insert a node at the end of the linked list


struct Node* insertAtEnd(struct Node* head, int value) {
struct Node* newNode = createNode(value);
if (head == NULL) {
return newNode;
}
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
return head;
}

// Function to insert a node at a specific location


struct Node* insertAtLocation(struct Node* head, int value, int position) {
if (position < 1) {
printf("Invalid position for insertion.\n");
return head;
}
if (position == 1 || head == NULL) {
return insertAtBeginning(head, value);
}
struct Node* newNode = createNode(value);
struct Node* current = head;
for (int i = 1; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Invalid position for insertion.\n");
return head;
}
newNode->next = current->next;
current->next = newNode;
return head;
}

// Function to delete a node from the beginning of the linked list


Data Structures Lab Workbook (MCL507) | 22
2023--25
struct Node* deleteFromBeginning(struct Node* head) {
if (head == NULL) {
printf("List is empty. Deletion not possible.\n");
return NULL;
}
struct Node* temp = head;
head = head->next;
free(temp);
return head;
}

// Function to delete a node from the end of the linked list


struct Node* deleteFromEnd(struct Node* head) {
if (head == NULL) {
printf("List is empty. Deletion not possible.\n");
return NULL;
}
if (head->next == NULL) {
free(head);
return NULL;
}
struct Node* current = head;
while (current->next->next != NULL) {
current = current->next;
}
free(current->next);
current->next = NULL;
return head;
}

// Function to delete a node from a specific location


struct Node* deleteFromLocation(struct Node* head, int position) {
if (position < 1 || head == NULL) {
printf("Invalid position for deletion.\n");
return head;
}
if (position == 1) {
struct Node* temp = head;
head = head->next;
free(temp);
return head;
}
struct Node* current = head;
for (int i = 1; i < position - 1 && current->next != NULL; i++) {
Data Structures Lab Workbook (MCL507) | 23
2023--25
current = current->next;
}
if (current->next == NULL) {
printf("Invalid position for deletion.\n");
return head;
}
struct Node* temp = current->next;
current->next = current->next->next;
free(temp);
return head;
}

// Function to display the linked list


void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;
int n, choice, value, position;
printf("Enter the number of nodes to create: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter the value for node %d: ", i + 1);
scanf("%d", &value);
head = insertAtEnd(head, value);
}
printf("\nLinked List Menu:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Insert at a specific location\n");
printf("4. Delete from the beginning\n");
printf("5. Delete from the end\n");
printf("6. Delete from a specific location\n");
printf("7. Display the linked list\n");
printf("8. Exit\n");
while (1) {
printf("Enter your choice: ");
scanf("%d", &choice);
Data Structures Lab Workbook (MCL507) | 24
2023--25

switch (choice) {
case 1:
printf("Enter the value to insert at the beginning: ");
scanf("%d", &value);
head = insertAtBeginning(head, value);
break;
case 2:
printf("Enter the value to insert at the end: ");
scanf("%d", &value);
head = insertAtEnd(head, value);
break;
case 3:
printf("Enter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert at: ");
scanf("%d", &position);
head = insertAtLocation(head, value, position);
break;
case 4:
head = deleteFromBeginning(head);
break;
case 5:
head = deleteFromEnd(head);
break;
case 6:
printf("Enter the position to delete from: ");
scanf("%d", &position);
head = deleteFromLocation(head, position);
break;
case 7:
printf("Linked List: ");
displayList(head);
break;
case 8:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Output – Screenshots (Student Work Area):
Data Structures Lab Workbook (MCL507) | 25
2023--25

Question Bank:

How Linked List is different from Arrays?

How to perform the following set of operations on a singly linked list (SLL):

 Swapping the first and last node of a singly linked list


 Pairwise swap elements of a given linked list
 Get the location of first and last occurrence of an element in a single LinkedList
 Remove duplicates from an unsorted linked list
 Delete alternate nodes of a Linked List.
Data Structures Lab Workbook (MCL507) | 26
2023--25
EXPERIMENT NO. 5

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Linked List and its basic operations

Outcome:

The students will be able to implement and use doubly linked list for solving various problems

Problem Statement:

Write a program to create a doubly linked list of n nodes and perform:

• Insertion

o At the beginning
o At the end
o At a specific location

• Deletion

o At the beginning
o At the end
o At a specific location

Background Study:
Data Structures Lab Workbook (MCL507) | 27
2023--25

A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together
with next pointer and data which are there in singly linked list.

Insertion Operation
A node can be added in three ways
1) At the front of the DLL
2) After a given node.
3) At the end of the DLL
1) Add a node at the front:

2) Add a node after a given node.:

3) Add a node at the end:


Data Structures Lab Workbook (MCL507) | 28
2023--25

Deletion Operation
The deletion of a node in a doubly-linked list can be divided into three main categories:
Suppose we have a double-linked list with elements 1, 2, and 3.

1. Delete the First Node of Doubly Linked List

Reset value node after the del_node (i.e. node two)

Reorganize the pointers


Finally, free the memory of del_node. And, the linked will look like this
Data Structures Lab Workbook (MCL507) | 29
2023--25

Final list

2. Deletion of the Inner Node

If del_node is an inner node (second node), we must have to reset the value of next and prev of the
nodes before and after the del_node.
For the node before the del_node (i.e. first node)
Assign the value of next of del_node to the next of the first node.
For the node after the del_node (i.e. third node)
Assign the value of prev of del_node to the prev of the third node.

Reorganize the pointers

Finally, we will free the memory of del_node. And, the final doubly linked list looks like this.
Data Structures Lab Workbook (MCL507) | 30
2023--25

Final list

3. Delete the Last Node of Doubly Linked List

In this case, we are deleting the last node with value 3 of the doubly linked list.
Here, we can simply delete the del_node and make the next of node before del_node point
to NULL.

Reorganize the pointers

The final doubly linked list looks like this.

Final list

Algorithm (Student Work Area):


Data Structures Lab Workbook (MCL507) | 31
2023--25
Algorithm for Creating a Doubly Linked List:

1. Create a structure definition for a doubly linked list node with three members: data, a pointer to
the previous node (prev), and a pointer to the next node (next).
2. Create a function 'createNode(value)' that takes an integer value as input and returns a new node
with the given value, a 'NULL' previous pointer, and a 'NULL' next pointer.
3. Initialize a head pointer to 'NULL' to represent an empty doubly linked list.
4. Read the number of nodes 'n' from the user.
5. For each node, perform the following:
a. Read a value from the user.
b. Create a new node with the value using the 'createNode' function.
c. Add the new node to the end of the doubly linked list using the 'insertAtEnd' function.

Algorithm for Inserting a Node at the Beginning:

1. Create a function 'insertAtBeginning(head, value)' that takes the current head pointer and a value
as input.
2. Create a new node with the given value using the createNode function.
3. If the linked list is not empty (head is not 'NULL'), set the previous pointer of the current head to
the new node.
4. Set the next pointer of the new node to the current head.
5. Update the head pointer to point to the new node.
6. Return the new head pointer.

Algorithm for Inserting a Node at the End:

1. Create a function 'insertAtEnd(head, value)' that takes the current head pointer and a value as
input.
2. Create a new node with the given value using the 'createNode' function.
3. If the linked list is empty (head is 'NULL'), set the head pointer to the new node and return it.
4. Otherwise, traverse the linked list to the last node.
5. Update the 'next' pointer of the last node to point to the new node.
6. Set the previous pointer of the new node to the last node.
7. Return the original head pointer.

Algorithm for Inserting a Node at a Specific Location:

1. Create a function 'insertAtLocation(head, value, position)' that takes the current head pointer, a
value, and a position as input.
2. Create a new node with the given value using the 'createNode' function.
3. If the position is less than 1, print an error message and return the original head pointer.
4. If the position is 1 or the linked list is empty (head is 'NULL'), insert the new node at the beginning
using the 'insertAtBeginning' function.
Data Structures Lab Workbook (MCL507) | 32
2023--25
5. Otherwise, traverse the linked list to the node just before the desired position.
6. Update the 'next' and prev pointers to insert the new node at the specified position.
7. Return the original head pointer

Algorithm for Deleting a Node from the Beginning:

1. Create a function 'deleteFromBeginning(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return 'NULL'.
3. Set the previous pointer of the new head (second node) to 'NULL'.
4. Free the memory of the original head.
5. Return the new head (second node).

Algorithm for Deleting a Node from the End:

1. Create a function 'deleteFromEnd(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return 'NULL'.
3. If the linked list has only one node, free its memory and set the head pointer to 'NULL.
4. Otherwise, traverse the linked list to the last node.
5. Update the next pointer of the previous node (second last) to 'NULL'.
6. Free the memory of the last node.
7. Return the original head pointer.

Algorithm for Deleting a Node from a Specific Location:

1. Create a function 'deleteFromLocation(head, position) that takes the current head pointer and a
position as input.
2. If the position is less than 1 or the linked list is empty (head is 'NULL'), print an error message and
return the original head pointer.
3. If the position is 1, delete the first node using the 'deleteFromBeginning' function.
4. Otherwise, traverse the linked list to the node at the desired position.
5. Update the 'next' and 'prev' pointers to remove the node at the specified position.
6. Free the memory of the removed node.
7. Return the original head pointer.

Code (Student Work Area):

#include <stdio.h>
#include <stdlib.h>

// Define a structure for a doubly linked list node


struct Node {
int data;
struct Node* prev;
struct Node* next;
};
Data Structures Lab Workbook (MCL507) | 33
2023--25
// Function to create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the beginning of the doubly linked list
struct Node* insertAtBeginning(struct Node* head, int value) {
struct Node* newNode = createNode(value);
if (head != NULL) {
head->prev = newNode;
}
newNode->next = head;
return newNode;
}
// Function to insert a node at the end of the doubly linked list
struct Node* insertAtEnd(struct Node* head, int value) {
struct Node* newNode = createNode(value);
struct Node* current = head;
if (head == NULL) {
return newNode;
}
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
return head;
}
// Function to insert a node at a specific location
struct Node* insertAtLocation(struct Node* head, int value, int position) {
if (position < 1) {
printf("Invalid position for insertion.\n");
return head;
}
if (position == 1 || head == NULL) {
return insertAtBeginning(head, value);
}
struct Node* newNode = createNode(value);
struct Node* current = head;
for (int i = 1; i < position - 1 && current->next != NULL; i++) {
current = current->next;
Data Structures Lab Workbook (MCL507) | 34
2023--25
}
newNode->next = current->next;
newNode->prev = current;
if (current->next != NULL) {
current->next->prev = newNode;
}
current->next = newNode;
return head;
}
// Function to delete a node from the beginning of the doubly linked list
struct Node* deleteFromBeginning(struct Node* head) {
if (head == NULL) {
printf("List is empty. Deletion not possible.\n");
return NULL;
}
struct Node* newHead = head->next;
if (newHead != NULL) {
newHead->prev = NULL;
}
free(head);
return newHead;
}
// Function to delete a node from the end of the doubly linked list
struct Node* deleteFromEnd(struct Node* head) {
if (head == NULL) {
printf("List is empty. Deletion not possible.\n");
return NULL;
}
if (head->next == NULL) {
free(head);
return NULL;
}
struct Node* current = head;
while (current->next->next != NULL) {
current = current->next;
}
free(current->next);
current->next = NULL;
return head;
}
// Function to delete a node from a specific location
struct Node* deleteFromLocation(struct Node* head, int position) {
if (position < 1 || head == NULL) {
printf("Invalid position for deletion.\n");
Data Structures Lab Workbook (MCL507) | 35
2023--25
return head;
}
if (position == 1) {
struct Node* newHead = head->next;
if (newHead != NULL) {
newHead->prev = NULL;
}
free(head);
return newHead;
}
struct Node* current = head;
for (int i = 1; i < position - 1 && current->next != NULL; i++) {
current = current->next;
}
if (current->next == NULL) {
printf("Invalid position for deletion.\n");
return head;
}
current->next = current->next->next;
if (current->next != NULL) {
current->next->prev = current;
}
return head;
}
// Function to display the doubly linked list from the beginning
void displayListFromBeginning(struct Node* head) {
struct Node* current = head;
printf("Doubly Linked List (from the beginning): ");
while (current != NULL) {
printf("%d <-> ", current->data);
current = current->next;
}
printf("NULL\n");
}

// Function to display the doubly linked list from the end


void displayListFromEnd(struct Node* head) {
struct Node* current = head;
if (head == NULL) {
printf("Doubly Linked List (from the end): NULL\n");
return;
}
while (current->next != NULL) {
current = current->next;
Data Structures Lab Workbook (MCL507) | 36
2023--25
}
printf("Doubly Linked List (from the end): ");
while (current != NULL) {
printf("%d <-> ", current->data);
current = current->prev;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;

int n, choice, value, position;


printf("Enter the number of nodes to create: ");
scanf("%d", &n);

for (int i = 0; i < n; i++) {


printf("Enter the value for node %d: ", i + 1);
scanf("%d", &value);
head = insertAtEnd(head, value);
}
printf("\nDoubly Linked List Menu:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Insert at a specific location\n");
printf("4. Delete from the beginning\n");
printf("5. Delete from the end\n");
printf("6. Delete from a specific location\n");
printf("7. Display the linked list from the beginning\n");
printf("8. Display the linked list from the end\n");
printf("9. Exit\n");
while (1) {
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to insert at the beginning: ");
scanf("%d", &value);
head = insertAtBeginning(head, value);
break;
case 2:
printf("Enter the value to insert at the end: ");
scanf("%d", &value);
Data Structures Lab Workbook (MCL507) | 37
2023--25
head = insertAtEnd(head, value);
break;
case 3:
printf("Enter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert at: ");
scanf("%d", &position);
head = insertAtLocation(head, value, position);
break;
case 4:
head = deleteFromBeginning(head);
break;
case 5:
head = deleteFromEnd(head);
break;
case 6:
printf("Enter the position to delete from: ");
scanf("%d", &position);
head = deleteFromLocation(head, position);
break;
case 7:
displayListFromBeginning(head);
break;
case 8:
displayListFromEnd(head);
break;
case 9:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;}
Output – Screenshots (Student Work Area):
Data Structures Lab Workbook (MCL507) | 38
2023--25

Question Bank:

1. What is Doubly Linked List?


2. What is the complexity of Traversal, Insertion and deletion
operations in doubly linked list?
Data Structures Lab Workbook (MCL507) | 39
2023--25
EXPERIMENT NO. 6

Student Name and Roll Number: Sandeep Kaushal 23MCA009

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Linked List and its basic operations

Outcome:

The students will be able to implement and use Circular linked list for solving various problems

Problem Statement:

Write a program to create a Circular linked list of n nodes and perform:

• Insertion

o At the beginning
o At the end
o At a specific location

• Deletion

o At the beginning
o At the end
o At a specific location

Background Study:
Data Structures Lab Workbook (MCL507) | 40
2023--25

Circular linked list is a linked list where all nodes are connected to form a circle. There is no
NULL at the end. A circular linked list can be a singly circular linked list or doubly circular
linked list.

Insertion
We can insert a node in a circular linked list either as a first node (empty list), in the beginning, in
the end, or in between the other nodes. Let us see each of these insertion operations using a pictorial
representation below.

#1) Insert in an empty list

When there are no nodes in circular list and the list is empty, the last pointer is null, then we insert a
new node N by pointing the last pointer to the node N as shown above. The next pointer of N will
point to the node N itself as there is only one node. Thus N becomes the first as well as last node in
the list.

#2) Insert at the beginning of the list


Data Structures Lab Workbook (MCL507) | 41
2023--25

As shown in the above representation, when we add a node at the beginning of the list, the next
pointer of the last node points to the new node N thereby making it a first node.

N->next = last->next
Last->next = N
#3) Insert at the end of the list

To insert a new node at the end of the list, we follow these steps:
N-> next = last ->next;
Data Structures Lab Workbook (MCL507) | 42
2023--25
last ->next = N
last = N
#4) Insert in between the list

Suppose we need to insert a new node N between N3 and N4, we first need to traverse the list and
locate the node after which the new node is to be inserted, in this case, its N3.

After the node is located, we perform the following steps.


N -> next = N3 -> next;
N3 -> next = N
This inserts a new node N after N3.

Deletion
The deletion operation of the circular linked list involves locating the node that is to be deleted and
then freeing its memory.

For this we maintain two additional pointers curr and prev and then traverse the list to locate the
node. The given node to be deleted can be the first node, the last node or the node in between.
Depending on the location we set the curr and prev pointers and then delete the curr node.

A pictorial representation of the deletion operation is shown below.

Algorithm (Student Work Area):


Data Structures Lab Workbook (MCL507) | 43
2023--25
Algorithm for Creating a Circular Linked List:

1. Create a structure definition for a circular linked list node with two members: data and a pointer to
the next node.
2. Create a function 'createNode(value)' that takes an integer value as input and returns a new node
with the given value and a NULL next pointer.
3. Initialize a head pointer to 'NULL' to represent an empty circular linked list.
4. Read the number of nodes 'n' from the user.
5. For each node, perform the following:
a. Read a value from the user.
b. Create a new node with the value using the 'createNode' function.
c. If the linked list is empty (head is 'NULL'), set the head pointer to the new node, making it
circular by having the next pointer point to itself.
d. Otherwise, traverse the linked list to the last node and set the next pointer of the last node
to the new node, making the list circular.

Algorithm for Inserting a Node at the Beginning:

1. Create a function 'insertAtBeginning(head, value)' that takes the current head pointer and a value
as input.
2. Create a new node with the given value using the 'createNode' function.
3. If the linked list is empty (head is 'NULL'), set the head pointer to the new node, making it circular
by having the next pointer point to itself.
4. Otherwise, traverse the linked list to the last node.
5. Update the next pointer of the last node to point to the new node.
6. Set the 'next' pointer of the new node to the current head.
7. Return the new head pointer.

Algorithm for Inserting a Node at the End:

1. Create a function 'insertAtEnd(head, value)' that takes the current head pointer and a value as
input.
2. Create a new node with the given value using the 'createNode' function.
3. If the linked list is empty (head is 'NULL'), set the head pointer to the new node, making it circular
by having the next pointer point to itself.
4. Otherwise, traverse the linked list to the last node.
5. Update the 'next' pointer of the last node to point to the new node.
6. Set the next pointer of the new node to the current head.
7. Return the original head pointer.

Algorithm for Inserting a Node at a Specific Location:

1. Create a function 'insertAtLocation(head, value, position)' that takes the current head pointer, a
Data Structures Lab Workbook (MCL507) | 44
2023--25
value, and a position as input.
2. Create a new node with the given value using the 'createNode' function.
3. If the position is less than 1, print an error message and return the original head pointer.
4. If the position is 1 or the linked list is empty (head is 'NULL'), insert the new node at the beginning
using the 'insertAtBeginning' function.
5. Otherwise, traverse the linked list to the node just before the desired position.
6. Update the 'next' pointers to insert the new node at the specified position.
7. Return the original head pointer.

Algorithm for Deleting a Node from the Beginning:

1. Create a function 'deleteFromBeginning(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return 'NULL'.
3. If the linked list has only one node (head points to itself), free its memory and return 'NULL'.
4. Traverse the linked list to the last node.
5. Update the 'next' pointer of the last node to point to the second node.
6. Free the memory of the original head.
7. Return the new head (second node).

Algorithm for Deleting a Node from the End:

1. Create a function 'deleteFromEnd(head)' that takes the current head pointer as input.
2. If the linked list is empty (head is 'NULL'), print an error message and return NULL.
3. If the linked list has only one node (head points to itself), free its memory and return 'NULL'.
4. Traverse the linked list to the second-to-last node.
5. Update the 'next' pointer of the second-to-last node to point to the first node (making it circular).
6. Free the memory of the last node.
7. Return the original head pointer.

Algorithm for Deleting a Node from a Specific Location:

1. Create a function 'deleteFromLocation(head, position)' that takes the current head pointer and a
position as input.
2. If the position is less than 1 or the linked list is empty (head is 'NULL'), print an error message and
return the original head pointer.
3. If the position is 1, delete the first node using the 'deleteFromBeginning' function.
4. Traverse the linked list to the node just before the desired position.
5. Update the 'next' pointers to remove the node at the specified position.
6. Free the memory of the removed node.
7. Return the original head pointer.

Code (Student Work Area):

#include <stdio.h>
Data Structures Lab Workbook (MCL507) | 45
2023--25
#include <stdlib.h>

// Define a structure for a circular linked list node

struct Node {

int data;

struct Node* next;

};

// Function to create a new node

struct Node* createNode(int value) {

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = value;

newNode->next = NULL;

return newNode;

// Function to insert a node at the beginning of the circular linked list

struct Node* insertAtBeginning(struct Node* head, int value) {

struct Node* newNode = createNode(value);

if (head == NULL) {

newNode->next = newNode; // Point to itself in a circular list

} else {

struct Node* current = head;

while (current->next != head) {

current = current->next;

}
Data Structures Lab Workbook (MCL507) | 46
2023--25
current->next = newNode;

newNode->next = head;

return newNode;

// Function to insert a node at the end of the circular linked list

struct Node* insertAtEnd(struct Node* head, int value) {

struct Node* newNode = createNode(value);

if (head == NULL) {

newNode->next = newNode; // Point to itself in a circular list

} else {

struct Node* current = head;

while (current->next != head) {

current = current->next;

current->next = newNode;

newNode->next = head;

return head;

// Function to insert a node at a specific location

struct Node* insertAtLocation(struct Node* head, int value, int position) {

if (position < 1) {

printf("Invalid position for insertion.\n");


Data Structures Lab Workbook (MCL507) | 47
2023--25
return head;

struct Node* newNode = createNode(value);

if (position == 1 || head == NULL) {

if (head == NULL) {

newNode->next = newNode; // Point to itself in a circular list

} else {

struct Node* current = head;

while (current->next != head) {

current = current->next;

current->next = newNode;

newNode->next = head;

return newNode;

struct Node* current = head;

int count = 1;

while (count < position - 1) {

current = current->next;

count++;

newNode->next = current->next;

current->next = newNode;

return head;
Data Structures Lab Workbook (MCL507) | 48
2023--25
}

// Function to delete a node from the beginning of the circular linked list

struct Node* deleteFromBeginning(struct Node* head) {

if (head == NULL) {

printf("List is empty. Deletion not possible.\n");

return NULL;

if (head->next == head) {

free(head);

return NULL;

struct Node* current = head;

while (current->next != head) {

current = current->next;

current->next = head->next;

struct Node* temp = head;

head = head->next;

free(temp);

return head;

// Function to delete a node from the end of the circular linked list

struct Node* deleteFromEnd(struct Node* head) {

if (head == NULL) {
Data Structures Lab Workbook (MCL507) | 49
2023--25
printf("List is empty. Deletion not possible.\n");

return NULL;

if (head->next == head) {

free(head);

return NULL;

struct Node* current = head;

struct Node* previous = NULL;

while (current->next != head) {

previous = current;

current = current->next;

previous->next = head;

free(current);

return head;

// Function to delete a node from a specific location

struct Node* deleteFromLocation(struct Node* head, int position) {

if (position < 1 || head == NULL) {

printf("Invalid position for deletion.\n");

return head;

if (position == 1) {
Data Structures Lab Workbook (MCL507) | 50
2023--25
if (head->next == head) {

free(head);

return NULL;

struct Node* current = head;

while (current->next != head) {

current = current->next;

current->next = head->next;

struct Node* temp = head;

head = head->next;

free(temp);

return head;

struct Node* current = head;

int count = 1;

struct Node* previous = NULL;

while (count < position) {

previous = current;

current = current->next;

count++;

previous->next = current->next;

free(current);
Data Structures Lab Workbook (MCL507) | 51
2023--25
return head;

// Function to display the circular linked list

void displayList(struct Node* head) {

if (head == NULL) {

printf("Circular Linked List: NULL\n");

return;

struct Node* current = head;

printf("Circular Linked List: ");

do {

printf("%d -> ", current->data);

current = current->next;

} while (current != head);

printf("... (back to the beginning)\n");

int main() {

struct Node* head = NULL;

int n, choice, value, position;

printf("Enter the number of nodes to create: ");

scanf("%d", &n);

for (int i = 0; i < n; i++) {


Data Structures Lab Workbook (MCL507) | 52
2023--25
printf("Enter the value for node %d: ", i + 1);

scanf("%d", &value);

head = insertAtEnd(head, value);

printf("\nCircular Linked List Menu:\n");

printf("1. Insert at the beginning\n");

printf("2. Insert at the end\n");

printf("3. Insert at a specific location\n");

printf("4. Delete from the beginning\n");

printf("5. Delete from the end\n");

printf("6. Delete from a specific location\n");

printf("7. Display the linked list\n");

printf("8. Exit\n");

while (1) {

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter the value to insert at the beginning: ");

scanf("%d", &value);

head = insertAtBeginning(head, value);

break;

case 2:
Data Structures Lab Workbook (MCL507) | 53
2023--25
printf("Enter the value to insert at the end: ");

scanf("%d", &value);

head = insertAtEnd(head, value);

break;

case 3:

printf("Enter the value to insert: ");

scanf("%d", &value);

printf("Enter the position to insert at: ");

scanf("%d", &position);

head = insertAtLocation(head, value, position);

break;

case 4:

head = deleteFromBeginning(head);

break;

case 5:

head = deleteFromEnd(head);

break;

case 6:

printf("Enter the position to delete from: ");

scanf("%d", &position);

head = deleteFromLocation(head, position);

break;

case 7:

displayList(head);
Data Structures Lab Workbook (MCL507) | 54
2023--25
break;

case 8:

exit(0);

default:

printf("Invalid choice. Please try again.\n");

} return 0;

Output – Screenshots (Student Work Area):


Data Structures Lab Workbook (MCL507) | 55
2023--25

Question Bank:

How Circular Linked List is different from Singly Linked List?

Analyze the complexity of Traversal, insertion and Deletion operations in Linked List?

EXPERIMENT NO. 7

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Stacks and its basic operations

Outcome:
Data Structures Lab Workbook (MCL507) | 56
2023--25
The students will be able to implement and use Stacks for solving various problems

Problem Statement:

Write a program to create a stack and perform:

 POP
 PUSH
 PEEK
 ISEMPTY
 ISFULL
1) Use Arrays for Implementation
2) Use Linked List for Implementation

Background:

Stacks are dynamic data structures that follow the Last In First Out (LIFO) principle. The last item to be
inserted into a stack is the first one to be deleted from it.

For example, you have a stack of trays on a table. The tray at the top of the stack is the first item to be
moved if you require a tray from that stack.

Inserting and deleting elements

Stacks have restrictions on the insertion and deletion of elements. Elements can be inserted or deleted only
from one end of the stack i.e. from the top. The element at the top is called the top element. The operations
of inserting and deleting elements are called push() and pop() respectively.

When the top element of a stack is deleted, if the stack remains non-empty, then the element just below the
previous top element becomes the new top element of the stack.

For example, in the stack of trays, if you take the tray on the top and do not replace it, then the second tray
automatically becomes the top element (tray) of that stack.

Features of stacks

 Dynamic data structures


 Do not have a fixed size
 Do not consume a fixed amount of memory
 Size of stack changes with each push() and pop() operation. Each push() and pop() operation
increases and decreases the size of the stack by 1, respectively.
Data Structures Lab Workbook (MCL507) | 57
2023--25

A stack can be visualized as follows:

Algorithm (Student Work Area):

1) Using Arrays for Implementation:


Initialization:
Input: Stack structure (struct StackUsingArray).
Algorithm:
Set the top index of the stack to -1.

Check if Stack is Empty:


Input: Stack structure (struct StackUsingArray).
Output: Boolean indicating whether the stack is empty.
Algorithm:
If the top index is -1, return true (indicating the stack is empty).
Otherwise, return false.
Data Structures Lab Workbook (MCL507) | 58
2023--25
Check if Stack is Full:
Input: Stack structure (struct StackUsingArray).
Output: Boolean indicating whether the stack is full.
Algorithm:
If the top index is equal to the maximum size of the stack minus 1, return true (indicating the stack
is full).
Otherwise, return false.

Push Element onto Stack:


Input: Stack structure (struct StackUsingArray), integer value to be pushed.
Algorithm:
Check if the stack is full.
If it is, print an overflow message and return.
Increment the top index.
Set the value at the new top index to the provided value.
Print a message indicating the value has been pushed onto the stack.

Pop Element from Stack:


Input: Stack structure (struct StackUsingArray).
Output: Integer value popped from the stack.
Algorithm:
Check if the stack is empty.
If it is, print an underflow message and return an invalid value.
Retrieve the value at the top index.
Decrement the top index.
Print a message indicating the value has been popped from the stack.
Return the popped value.

Peek at the Top Element of the Stack:


Input: Stack structure (struct StackUsingArray).
Output: Integer value at the top of the stack.
Algorithm:
Check if the stack is empty.
If it is, print a message that the stack is empty and return an invalid value.
Return the value at the top index.

Code (Student Work Area):


Data Structures Lab Workbook (MCL507) | 59
2023--25
#include <stdio.h>

#define MAX_SIZE 5

struct StackUsingArray {
int stack[MAX_SIZE];
int top;
};

void initialize(struct StackUsingArray* s) {


s->top = -1;
}

int is_empty(struct StackUsingArray* s) {


return s->top == -1;
}

int is_full(struct StackUsingArray* s) {


return s->top == MAX_SIZE - 1;
}

void push(struct StackUsingArray* s, int value) {


if (is_full(s)) {
printf("Stack Overflow. Cannot push element.\n");
return;
}
s->top++;
s->stack[s->top] = value;
printf("Pushed %d to the stack.\n", value);
}

int pop(struct StackUsingArray* s) {


if (is_empty(s)) {
printf("Stack Underflow. Cannot pop element.\n");
return -1; // Assuming -1 represents an invalid value
}
int popped_value = s->stack[s->top];
s->top--;
printf("Popped %d from the stack.\n", popped_value);
return popped_value;
}

int peek(struct StackUsingArray* s) {


if (is_empty(s)) {
Data Structures Lab Workbook (MCL507) | 60
2023--25
printf("Stack is empty. Cannot peek.\n");
return -1; // Assuming -1 represents an invalid value
}
return s->stack[s->top];
}

int main() {
struct StackUsingArray stack;
initialize(&stack);

push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
printf("Peek: %d\n", peek(&stack));

pop(&stack);
pop(&stack);
pop(&stack);
pop(&stack);

return 0;
}

Output – Screenshots (Student Work Area):


Data Structures Lab Workbook (MCL507) | 61
2023--25

Question Bank:

What are Stacks?

What are the applications of stacks?

EXPERIMENT NO. 8

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):
Data Structures Lab Workbook (MCL507) | 62
2023--25

To familiarize the students with linear data structure Stacks and its applications.

Outcome:

The students will be able to implement and use Stacks for solving various problems

Problem Statement:

Write a program to create a stack and perform:

Reversal of a sentence using stack.

Given a string str consisting of a sentence, the task is to reverse the entire sentence word by word.

Examples:

Input: str = “data structures and algorithms”


Output: algorithms and structures data

Background:

Stacks are dynamic data structures that follow the Last In First Out (LIFO) principle. The last item to be
inserted into a stack is the first one to be deleted from it.

For example, you have a stack of trays on a table. The tray at the top of the stack is the first item to be
moved if you require a tray from that stack.

Inserting and deleting elements

Stacks have restrictions on the insertion and deletion of elements. Elements can be inserted or deleted only
from one end of the stack i.e. from the top. The element at the top is called the top element. The operations
of inserting and deleting elements are called push() and pop() respectively.

When the top element of a stack is deleted, if the stack remains non-empty, then the element just below the
previous top element becomes the new top element of the stack.

For example, in the stack of trays, if you take the tray on the top and do not replace it, then the second tray
automatically becomes the top element (tray) of that stack.

Features of stacks

 Dynamic data structures


 Do not have a fixed size
 Do not consume a fixed amount of memory
 Size of stack changes with each push() and pop() operation. Each push() and pop() operation
Data Structures Lab Workbook (MCL507) | 63
2023--25
increases and decreases the size of the stack by 1, respectively.

A stack can be visualized as follows:

Algorithm (Student Work Area):

Step 1: Initialize Stack


 Create a stack data structure to hold words. Initialize the stack to be empty.
Step 2: Process Words
 Take a sentence as input (e.g., "This is a sample sentence.").
 Use a tokenizer to split the sentence into words using space as a delimiter.
 For each word encountered:
 Push the word onto the stack.
Step 3: Print in Reverse Order
 While the stack is not empty:
 Pop the top word from the stack.
 Print the popped word.

Code (Student Work Area):

#include <stdio.h>
Data Structures Lab Workbook (MCL507) | 64
2023--25
#include <string.h>

#define MAX_WORDS 100


#define MAX_WORD_LENGTH 50

struct Stack {
char items[MAX_WORDS][MAX_WORD_LENGTH];
int top;
};

void initialize(struct Stack* stack) {


stack->top = -1;
}

int is_empty(struct Stack* stack) {


return stack->top == -1;
}

int is_full(struct Stack* stack) {


return stack->top == MAX_WORDS - 1;
}

void push(struct Stack* stack, const char* word) {


if (!is_full(stack)) {
stack->top++;
strcpy(stack->items[stack->top], word);
} else {
printf("Stack Overflow. Cannot push element.\n");
}
}

void pop(struct Stack* stack) {


if (!is_empty(stack)) {
printf("%s\n", stack->items[stack->top]);
stack->top--;
} else {
printf("Stack Underflow. Cannot pop element.\n");
}
}

int main() {
struct Stack wordStack;
initialize(&wordStack);
Data Structures Lab Workbook (MCL507) | 65
2023--25
char sentence[] = "This is a sample sentence.";
char* token = strtok(sentence, " "); // Split the sentence into words

while (token != NULL) {


push(&wordStack, token);
token = strtok(NULL, " ");
}

printf("Popped words from the stack:\n");


while (!is_empty(&wordStack)) {
pop(&wordStack);
}

return 0;
}

Output – Screenshots (Student Work Area):

Question Bank:

What are Stacks?


Data Structures Lab Workbook (MCL507) | 66
2023--25
How we can split a sentence and push it into the stack?
Data Structures Lab Workbook (MCL507) | 67
2023--25
EXPERIMENT NO. 9

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Stacks and its applications.

Outcome:

The students will be able to implement and use Stacks for solving various problems

Problem Statement:

Write a program to check whether the parenthesis in the expression are balanced or not.

Given a string str consisting of an expression

Examples:

Input: str = (a+b)*c

Output: Parenthesis Balanced

Background:

Stacks are dynamic data structures that follow the Last In First Out (LIFO) principle. The last item to be
inserted into a stack is the first one to be deleted from it.

For example, you have a stack of trays on a table. The tray at the top of the stack is the first item to be
moved if you require a tray from that stack.
Data Structures Lab Workbook (MCL507) | 68
2023--25

Inserting and deleting elements

Stacks have restrictions on the insertion and deletion of elements. Elements can be inserted or deleted only
from one end of the stack i.e. from the top. The element at the top is called the top element. The operations
of inserting and deleting elements are called push() and pop() respectively.

When the top element of a stack is deleted, if the stack remains non-empty, then the element just below the
previous top element becomes the new top element of the stack.

For example, in the stack of trays, if you take the tray on the top and do not replace it, then the second tray
automatically becomes the top element (tray) of that stack.

Features of stacks

 Dynamic data structures


 Do not have a fixed size
 Do not consume a fixed amount of memory
 Size of stack changes with each push() and pop() operation. Each push() and pop() operation
increases and decreases the size of the stack by 1, respectively.

A stack can be visualized as follows:

Algorithm (Student Work Area):


Data Structures Lab Workbook (MCL507) | 69
2023--25
1. Initialize a stack to hold opening parentheses.
2. For each character in the expression:
 If the current character is an opening parenthesis ('(', '[', '{'), push it onto the
stack.
 If the current character is a closing parenthesis (')', ']', '}'):
 If the stack is empty, return false (unmatched closing parenthesis).
 Pop the top character from the stack.
 If the popped character is not the corresponding opening parenthesis
for the current closing parenthesis, return false (mismatched
parentheses).
3. After scanning the entire expression:
 If the stack is empty, return true (all opening parentheses have matching
closing parentheses).
 If the stack is not empty, return false (unmatched opening parentheses).

Code (Student Work Area):

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_SIZE 100

struct Stack {
char items[MAX_SIZE];
int top;
};

void initialize(struct Stack* stack) {


stack->top = -1;
}

int isEmpty(struct Stack* stack) {


return stack->top == -1;
}

int isFull(struct Stack* stack) {


return stack->top == MAX_SIZE - 1;
}

void push(struct Stack* stack, char value) {


Data Structures Lab Workbook (MCL507) | 70
2023--25
if (isFull(stack)) {
printf("Stack Overflow\n");
exit(EXIT_FAILURE);
}

stack->items[++stack->top] = value;
}

char pop(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack Underflow\n");
exit(EXIT_FAILURE);
}

return stack->items[stack->top--];
}

bool isBalanced(char expression[]) {


struct Stack stack;
initialize(&stack);

for (int i = 0; expression[i] != '\0'; i++) {


if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{') {
push(&stack, expression[i]);
} else if (expression[i] == ')' || expression[i] == ']' || expression[i] == '}') {
if (isEmpty(&stack)) {
return false; // Closing parenthesis with no matching opening parenthesis
}

char popped = pop(&stack);


if ((expression[i] == ')' && popped != '(') ||
(expression[i] == ']' && popped != '[') ||
(expression[i] == '}' && popped != '{')) {
return false; // Mismatched opening and closing parenthesis
}
}
}

return isEmpty(&stack); // Check if all opening parentheses are matched


}

int main() {
char expression[MAX_SIZE];
Data Structures Lab Workbook (MCL507) | 71
2023--25
printf("Enter an expression: ");
fgets(expression, sizeof(expression), stdin);

// Remove the newline character at the end of the input


expression[strcspn(expression, "\n")] = '\0';

if (isBalanced(expression)) {
printf("Parentheses are balanced.\n");
} else {
printf("Parentheses are not balanced.\n");
}

return 0;
}

Output – Screenshots (Student Work Area):

Q: How a stack helps in syntax analysis or compilation of a program?


Data Structures Lab Workbook (MCL507) | 72
2023--25

EXPERIMENT NO. 10

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Stacks and its applications.

Outcome:

The students will be able to implement and use Stacks for solving various problems

Problem Statement:
Data Structures Lab Workbook (MCL507) | 73
2023--25
Write a program to convert Infix expression into Postfix.

Given a string str consisting of an infix expression, convert it into Postfix

Examples:

Input: str = (a+b)*c

Output: ab+*

Background:

Any expression can be represented using three types of expressions (Infix, Postfix, and Prefix). We
can also convert one type of expression to another type of expression like Infix to Postfix, Infix to
Prefix, Postfix to Prefix and vice versa.

Infix to postfix conversion


Scan through an expression, getting one token at a time.

1 Fix a priority level for each operator. For example, from high to low:
3. - (unary negation)
2. */
1. + - (subtraction)

Thus, high priority corresponds to high number in the table.

2 If the token is an operand, do not stack it. Pass it to the output.

3 If token is an operator or parenthesis, do the following:


-- Pop the stack until you find a symbol of lower priority number than the current one. An incoming left
parenthesis will be considered to have higher priority than any other symbol. A left parenthesis on the stack
will not be removed unless an incoming right parenthesis is found.
The popped stack elements will be written to output.

--Stack the current symbol.

-- If a right parenthesis is the current symbol, pop the stack down to (and including) the first left
parenthesis. Write all the symbols except the left parenthesis to the output (i.e. write the operators to the
output).

-- After the last token is read, pop the remainder of the stack and write any symbol (except left
parenthesis) to output.

Example:
Data Structures Lab Workbook (MCL507) | 74
2023--25

Convert A * (B + C) * D to postfix notation.

Move Curren Ttoken Stack Output


1 A empty A
2 * * A
3 ( (* A
4 B (* AB
5 + +(* AB
6 C +(* ABC
7 ) * ABC+
8 * * ABC+*
9 D * ABC+*D
10 empty
Algorithm (Student Work Area):

Consider the infix expression: 3+4*(2-7)/5

1. Initialize an empty stack.


2. Scan the infix expression:
 Output: 3
 Push: +
 Output: 3 4
 Pop and output: 3 4 *
 Push: (
 Output: 3 4 * 2
 Pop and output: 3 4 * 2 7 -
 Pop: ( (no output)
 Pop and output: 3 4 * 2 7 - /
 Output: 3 4 * 2 7 - / 5
 Pop and output: 3 4 * 2 7 - / 5 +
3. Pop any remaining operators: 3 4 * 2 7 - / 5 +

The resulting postfix expression is: 34*27-/5+


Data Structures Lab Workbook (MCL507) | 75
2023--25

Code (Student Work Area):

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

#include <ctype.h>

#define MAX_SIZE 100

struct Stack {

char items[MAX_SIZE];

int top;

};

void initialize(struct Stack* stack) {

stack->top = -1;

int isEmpty(struct Stack* stack) {

return stack->top == -1;

int isFull(struct Stack* stack) {


Data Structures Lab Workbook (MCL507) | 76
2023--25
return stack->top == MAX_SIZE - 1;

void push(struct Stack* stack, char value) {

if (isFull(stack)) {

printf("Stack Overflow\n");

exit(EXIT_FAILURE);

stack->items[++stack->top] = value;

char pop(struct Stack* stack) {

if (isEmpty(stack)) {

printf("Stack Underflow\n");

exit(EXIT_FAILURE);

return stack->items[stack->top--];

char peek(struct Stack* stack) {

if (isEmpty(stack)) {

return '\0';
Data Structures Lab Workbook (MCL507) | 77
2023--25
}

return stack->items[stack->top];

int isOperator(char symbol) {

return (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/');

int getPrecedence(char operator) {

if (operator == '+' || operator == '-')

return 1;

else if (operator == '*' || operator == '/')

return 2;

return 0;

void infixToPostfix(char infix[], char postfix[]) {

struct Stack stack;

initialize(&stack);

int i, j;

i = j = 0;
Data Structures Lab Workbook (MCL507) | 78
2023--25
while (infix[i] != '\0') {

if (infix[i] == ' ' || infix[i] == '\t') {

// Ignore whitespaces

i++;

} else if (isdigit(infix[i]) || isalpha(infix[i])) {

// If operand, add to postfix expression

postfix[j++] = infix[i++];

} else if (isOperator(infix[i])) {

// If operator, pop and add to postfix while stack has higher or equal precedence operators

while (!isEmpty(&stack) && getPrecedence(peek(&stack)) >= getPrecedence(infix[i])) {

postfix[j++] = pop(&stack);

push(&stack, infix[i++]);

} else if (infix[i] == '(') {

// If open parenthesis, push onto stack

push(&stack, infix[i++]);

} else if (infix[i] == ')') {

// If close parenthesis, pop and add to postfix until open parenthesis is encountered

while (!isEmpty(&stack) && peek(&stack) != '(') {

postfix[j++] = pop(&stack);

if (!isEmpty(&stack) && peek(&stack) == '(') {

pop(&stack); // Pop the '('

}
Data Structures Lab Workbook (MCL507) | 79
2023--25
i++;

} else {

printf("Invalid character in the infix expression.\n");

exit(EXIT_FAILURE);

// Pop and add remaining operators from stack to postfix

while (!isEmpty(&stack)) {

postfix[j++] = pop(&stack);

postfix[j] = '\0'; // Null-terminate the postfix expression

int main() {

char infix[MAX_SIZE], postfix[MAX_SIZE];

printf("Enter an infix expression: ");

fgets(infix, sizeof(infix), stdin);

// Remove the newline character at the end of the input

infix[strcspn(infix, "\n")] = '\0';


Data Structures Lab Workbook (MCL507) | 80
2023--25
infixToPostfix(infix, postfix);

printf("Postfix expression: %s\n", postfix);

return 0;

Output – Screenshots (Student Work Area):

QUESTION BANK:

1. Why conversion is required?


2. How we can convert infix to prefix and prefix to postfix?
Data Structures Lab Workbook (MCL507) | 81
2023--25

EXPERIMENT NO. 11

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Stacks and its application Recursion.

Outcome:

The students will be able to implement and use Stacks for solving Recursion problems

Problem Statement:

Write a program to implement Tower of Hanoi.

Background:

Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings is as depicted −
Data Structures Lab Workbook (MCL507) | 82
2023--25

These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one. There are other variations of the puzzle where the number of
disks increase, but the tower count remains the same.

Rules
The mission is to move all the disks to some another tower without violating the sequence
of arrangement. A few rules to be followed for Tower of Hanoi are −

 Only one disk can be moved among the towers at any given time.
 Only the "top" disk can be removed.
 No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps

.
Algorithm (Student Work Area):

1. Function moveDisk(disk, source, destination):


 Output the move: "Move disk 'disk' from peg 'source' to peg 'destination'."
2. Function towerOfHanoi(n, source, auxiliary, destination):
 Base Case:
 If n is 1:
 Call moveDisk(1, source, destination) .
 Return.
 Recursive Case:
 Move n-1 disks from the source peg to the auxiliary peg using the
destination peg as the auxiliary.
 Call moveDisk(n, source, destination) .
 Move n-1 disks from the auxiliary peg to the destination peg using the
source peg as the auxiliary.
Data Structures Lab Workbook (MCL507) | 83
2023--25
3. Main Program:
 Read the number of disks numDisks from the user.
 If numDisks is less than or equal to 0, print an error message and exit.
 Call towerOfHanoi(numDisks, 'A', 'B', 'C') to solve the Tower of Hanoi problem.

Code (Student Work Area):

#include <stdio.h>

// Function to move a disk from source peg to destination peg


void moveDisk(int disk, char source, char destination) {
printf("Move disk %d from %c to %c\n", disk, source, destination);
}

// Function to solve Tower of Hanoi with 'n' disks


void towerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
moveDisk(1, source, destination);
return;
}

towerOfHanoi(n - 1, source, destination, auxiliary);


moveDisk(n, source, destination);
towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
int numDisks;

printf("Enter the number of disks: ");


scanf("%d", &numDisks);

if (numDisks <= 0) {
printf("Number of disks should be greater than 0.\n");
return 1;
}

// Towers are represented by characters 'A', 'B', 'C'


towerOfHanoi(numDisks, 'A', 'B', 'C');

return 0;
}
Data Structures Lab Workbook (MCL507) | 84
2023--25

Output – Screenshots (Student Work Area):

QUESTION BANK:

1. What is Recursion?
2. What is Base condition?
3. What are the number of steps required to solve n-Disc problem?
Data Structures Lab Workbook (MCL507) | 85
2023--25

EXPERIMENT NO. 12

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Queue and its applications.

Outcome:

The students will be able to implement and use Queues for solving various problems

Problem Statement:

Write a program to implement Following operations using Queue:

1. Enqueue()
2. Dequeue()
3. Isfull()
4. Isempty()
5. Peek()
Data Structures Lab Workbook (MCL507) | 86
2023--25
a) Using array implementation
b) Using Linked List Implementation

Background:

Queue is also an abstract data type or a linear data structure, just like stack data structure, in which
the first element is inserted from one end called the REAR(also called tail), and the removal of
existing element takes place from the other end called as FRONT(also called head).

This makes queue as FIFO(First in First Out) data structure, which means that element inserted
first will be removed first.

Which is exactly how queue system works in real world. If you go to a ticket counter to buy movie
tickets, and are first in the queue, then you will be the first one to get the tickets. Right? Same is the
case with Queue data structure. Data inserted first, will leave the queue first.

The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

Basic features of Queue

1. Like stack, queue is also an ordered list of elements of similar data types.

2. Queue is a FIFO( First in First Out ) structure.

3. Once a new element is inserted into the Queue, all the elements inserted before the new
Data Structures Lab Workbook (MCL507) | 87
2023--25
element in the queue must be removed, to remove the new element.

4. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Algorithm (Student Work Area):

Code (Student Work Area):

Array implementation:
#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 5

struct Queue {
int arr[MAX_SIZE];
int front, rear;
};

// Initialize the queue


void initializeQueue(struct Queue *q) {
q->front = -1;
q->rear = -1;
}

// Check if the queue is full


bool isFull(struct Queue *q) {
return q->rear == MAX_SIZE - 1;
}

// Check if the queue is empty


bool isEmpty(struct Queue *q) {
return q->front == -1;
}

// Add an element to the queue (enqueue)


void enqueue(struct Queue *q, int item) {
Data Structures Lab Workbook (MCL507) | 88
2023--25
if (isFull(q)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}

if (isEmpty(q)) {
q->front = 0;
}

q->rear = q->rear + 1;
q->arr[q->rear] = item;
printf("Enqueued element: %d\n", item);
}

// Remove an element from the queue (dequeue)


void dequeue(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot dequeue.\n");
return;
}

printf("Dequeued element: %d\n", q->arr[q->front]);

if (q->front == q->rear) {
initializeQueue(q);
} else {
q->front = q->front + 1;
}
}

// Peek at the front of the queue


void peek(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot peek.\n");
return;
}

printf("Front element: %d\n", q->arr[q->front]);


}

// Driver program
int main() {
struct Queue q;
initializeQueue(&q);
Data Structures Lab Workbook (MCL507) | 89
2023--25

enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);

peek(&q);

dequeue(&q);
dequeue(&q);

peek(&q);

return 0;
}
Link list implementation:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct Node {
int data;
struct Node *next;
};

struct Queue {
struct Node *front, *rear;
};

// Initialize the queue


void initializeQueue(struct Queue *q) {
q->front = q->rear = NULL;
}

// Check if the queue is empty


bool isEmpty(struct Queue *q) {
return q->front == NULL;
}

// Add an element to the queue (enqueue)


void enqueue(struct Queue *q, int item) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = item;
newNode->next = NULL;
Data Structures Lab Workbook (MCL507) | 90
2023--25
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}

printf("Enqueued element: %d\n", item);


}

// Remove an element from the queue (dequeue)


void dequeue(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot dequeue.\n");
return;
}

struct Node *temp = q->front;


q->front = q->front->next;

printf("Dequeued element: %d\n", temp->data);


free(temp);

if (q->front == NULL) {
q->rear = NULL;
}
}

// Peek at the front of the queue


void peek(struct Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot peek.\n");
return;
}

printf("Front element: %d\n", q->front->data);


}

// Driver program
int main() {
struct Queue q;
initializeQueue(&q);

enqueue(&q, 10);
Data Structures Lab Workbook (MCL507) | 91
2023--25
enqueue(&q, 20);
enqueue(&q, 30);

peek(&q);

dequeue(&q);
dequeue(&q);

peek(&q);

return 0;
}

Output – Screenshots (Student Work Area):


Data Structures Lab Workbook (MCL507) | 92
2023--25

QUESTION BANK:

1. What are the applications of queues?


2. Queues can be implemented with the help of stack. How?
Data Structures Lab Workbook (MCL507) | 93
2023--25
EXPERIMENT NO. 13

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with linear data structure Circular Queue and its applications.

Outcome:

The students will be able to implement and use Circular Queues for solving various problems

Problem Statement:

Write a program to implement Following operations using Circular Queue:

1. Enqueue()
2. Dequeue()

Using array implementation

Background:

Queue is also an abstract data type or a linear data structure, just like stack data structure, in which
the first element is inserted from one end called the REAR(also called tail), and the removal of
existing element takes place from the other end called as FRONT(also called head).

This makes queue as FIFO(First in First Out) data structure, which means that element inserted
first will be removed first.

Which is exactly how queue system works in real world. If you go to a ticket counter to buy movie
Data Structures Lab Workbook (MCL507) | 94
2023--25
tickets, and are first in the queue, then you will be the first one to get the tickets. Right? Same is the
case with Queue data structure. Data inserted first, will leave the queue first.

The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.
Data Structures Lab Workbook (MCL507) | 95
2023--25

Basic features of Queue

5. Like stack, queue is also an ordered list of elements of similar data types.
Data Structures Lab Workbook (MCL507) | 96
2023--25
6. Queue is a FIFO( First in First Out ) structure.

7. Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.

8. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Algorithm (Student Work Area):

Initialization Algorithm:
1. Create a structure for the circular queue, including an array to store elements, and front and
rear pointers.
2. Set the front and rear pointers to -1 to indicate an empty circular queue.
Enqueue Algorithm:
1. Check if the circular queue is full.
2. If the circular queue is empty, set both front and rear pointers to 0.
3. If the rear pointer is at the end, move it to the beginning (circularly).
4. Increment the rear pointer.
5. Place the new element at the updated rear position.
Dequeue Algorithm:
1. Check if the circular queue is empty.
2. Output the element at the front.
3. If the front and rear pointers are the same, indicating the last element, reset the circular
queue.
4. If the front pointer is at the end, move it to the beginning (circularly).
5. Increment the front pointer.
Is Full Algorithm:
1. Check if the front is at the beginning and the rear is at the end (circularly adjacent) or if
front is one less than rear (circularly).
2. If either condition is true, the circular queue is full.
Is Empty Algorithm:
1. Check if the front pointer is -1.
2. If true, the circular queue is empty.
Data Structures Lab Workbook (MCL507) | 97
2023--25

Code (Student Work Area):

#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 5

struct CircularQueue {
int arr[MAX_SIZE];
int front, rear;
};

// Initialize the circular queue


void initializeCircularQueue(struct CircularQueue *cq) {
cq->front = -1;
cq->rear = -1;
}

// Check if the circular queue is full


bool isFull(struct CircularQueue *cq) {
return (cq->front == 0 && cq->rear == MAX_SIZE - 1) || (cq->front == cq->rear + 1);
}

// Check if the circular queue is empty


bool isEmpty(struct CircularQueue *cq) {
return cq->front == -1;
}

// Add an element to the circular queue


void enqueue(struct CircularQueue *cq, int item) {
if (isFull(cq)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}

if (isEmpty(cq)) {
cq->front = 0;
cq->rear = 0;
} else if (cq->rear == MAX_SIZE - 1) {
cq->rear = 0;
} else {
cq->rear = cq->rear + 1;
}
Data Structures Lab Workbook (MCL507) | 98
2023--25

cq->arr[cq->rear] = item;
printf("Enqueued element: %d\n", item);
}

// Remove an element from the circular queue


void dequeue(struct CircularQueue *cq) {
if (isEmpty(cq)) {
printf("Queue is empty. Cannot dequeue.\n");
return;
}

printf("Dequeued element: %d\n", cq->arr[cq->front]);

if (cq->front == cq->rear) {
initializeCircularQueue(cq);
} else if (cq->front == MAX_SIZE - 1) {
cq->front = 0;
} else {
cq->front = cq->front + 1;
}
}

// Driver program
int main() {
struct CircularQueue cq;
initializeCircularQueue(&cq);

enqueue(&cq, 10);
enqueue(&cq, 20);
enqueue(&cq, 30);
enqueue(&cq, 40);
enqueue(&cq, 50);

dequeue(&cq);
dequeue(&cq);

enqueue(&cq, 60);
enqueue(&cq, 70);

return 0;
}
Output – Screenshots (Student Work Area):
Data Structures Lab Workbook (MCL507) | 99
2023--25

QUESTION BANK:

1. What are the applications of Circular queues?


2. What is the complexity of all operations in Circular Queue?

EXPERIMENT NO. 14

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:
Data Structures Lab Workbook (MCL507) |
100
2023--25

Objective(s):

To familiarize the students with linear data structure Doubly Ended Queue and its applications.

Outcome:

The students will be able to implement and use Doubly ended Queues for solving various problems

Problem Statement:

Write a program to implement Following operations using Doubly ended Queue:

1. Enqueue()
2. Dequeue()
3. Isfull()
4. Isempty()
5. Peek()

Using array implementation

Background:

Queue is also an abstract data type or a linear data structure, just like stack data structure, in which
the first element is inserted from one end called the REAR(also called tail), and the removal of
existing element takes place from the other end called as FRONT(also called head).

This makes queue as FIFO(First in First Out) data structure, which means that element inserted
first will be removed first.

Which is exactly how queue system works in real world. If you go to a ticket counter to buy movie
tickets, and are first in the queue, then you will be the first one to get the tickets. Right? Same is the
case with Queue data structure. Data inserted first, will leave the queue first.

The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.
Data Structures Lab Workbook (MCL507) |
101
2023--25

Basic features of Queue

9. Like stack, queue is also an ordered list of elements of similar data types.

10. Queue is a FIFO( First in First Out ) structure.

11. Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.

12. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Algorithm (Student Work Area):

Initialization Algorithm:
1. Create a structure for the deque, including an array to store elements, and front and rear
pointers.
2. Set the front and rear pointers to -1 to indicate an empty deque.
Enqueue at Front Algorithm:
1. Check if the deque is full.
2. If the deque is empty, set both front and rear pointers to 0.
3. If the front pointer is at the beginning, move it to the end.
4. Decrement the front pointer.
5. Place the new element at the updated front position.
Enqueue at Rear Algorithm:
Data Structures Lab Workbook (MCL507) |
102
2023--25
1. Check if the deque is full.
2. If the deque is empty, set both front and rear pointers to 0.
3. If the rear pointer is at the end, move it to the beginning.
4. Increment the rear pointer.
5. Place the new element at the updated rear position.
Dequeue from Front Algorithm:
1. Check if the deque is empty.
2. Output the element at the front.
3. If the front and rear pointers are the same, indicating the last element, reset the deque.
4. If the front pointer is at the end, move it to the beginning.
5. Increment the front pointer.
Dequeue from Rear Algorithm:
1. Check if the deque is empty.
2. Output the element at the rear.
3. If the front and rear pointers are the same, indicating the last element, reset the deque.
4. If the rear pointer is at the beginning, move it to the end.
5. Decrement the rear pointer.
Is Full Algorithm:
1. Check if the front is at the beginning and the rear is at the end (circularly adjacent) or if
front is one less than rear.
2. If either condition is true, the deque is full.
Is Empty Algorithm:
1. Check if the front pointer is -1.
2. If true, the deque is empty.
Peek at Front Algorithm:
1. Check if the deque is empty.
2. Output the element at the front.
Peek at Rear Algorithm:
1. Check if the deque is empty.
2. Output the element at the rear.
Data Structures Lab Workbook (MCL507) |
103
2023--25

Code (Student Work Area):

#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 5

struct Deque {
int arr[MAX_SIZE];
int front, rear;
};

// Initialize the deque


void initializeDeque(struct Deque *dq) {
dq->front = -1;
dq->rear = -1;
}

// Check if the deque is full


bool isFull(struct Deque *dq) {
return (dq->front == 0 && dq->rear == MAX_SIZE - 1) || (dq->front == dq->rear + 1);
}

// Check if the deque is empty


bool isEmpty(struct Deque *dq) {
return dq->front == -1;
}

// Add an element to the front of the deque


void enqueueFront(struct Deque *dq, int item) {
if (isFull(dq)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}

if (isEmpty(dq)) {
dq->front = 0;
dq->rear = 0;
} else if (dq->front == 0) {
dq->front = MAX_SIZE - 1;
Data Structures Lab Workbook (MCL507) |
104
2023--25
} else {
dq->front = dq->front - 1;
}

dq->arr[dq->front] = item;
printf("Enqueued element at front: %d\n", item);
}

// Add an element to the rear of the deque


void enqueueRear(struct Deque *dq, int item) {
if (isFull(dq)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}

if (isEmpty(dq)) {
dq->front = 0;
dq->rear = 0;
} else if (dq->rear == MAX_SIZE - 1) {
dq->rear = 0;
} else {
dq->rear = dq->rear + 1;
}

dq->arr[dq->rear] = item;
printf("Enqueued element at rear: %d\n", item);
}

// Remove an element from the front of the deque


void dequeueFront(struct Deque *dq) {
if (isEmpty(dq)) {
printf("Queue is empty. Cannot dequeue from front.\n");
return;
}

printf("Dequeued element from front: %d\n", dq->arr[dq->front]);

if (dq->front == dq->rear) {
initializeDeque(dq);
} else if (dq->front == MAX_SIZE - 1) {
dq->front = 0;
} else {
dq->front = dq->front + 1;
Data Structures Lab Workbook (MCL507) |
105
2023--25
}
}

// Remove an element from the rear of the deque


void dequeueRear(struct Deque *dq) {
if (isEmpty(dq)) {
printf("Queue is empty. Cannot dequeue from rear.\n");
return;
}

printf("Dequeued element from rear: %d\n", dq->arr[dq->rear]);

if (dq->front == dq->rear) {
initializeDeque(dq);
} else if (dq->rear == 0) {
dq->rear = MAX_SIZE - 1;
} else {
dq->rear = dq->rear - 1;
}
}

// Peek at the front of the deque


void peekFront(struct Deque *dq) {
if (isEmpty(dq)) {
printf("Queue is empty. Cannot peek at front.\n");
return;
}

printf("Front element: %d\n", dq->arr[dq->front]);


}

// Peek at the rear of the deque


void peekRear(struct Deque *dq) {
if (isEmpty(dq)) {
printf("Queue is empty. Cannot peek at rear.\n");
return;
}

printf("Rear element: %d\n", dq->arr[dq->rear]);


}

// Driver program
int main() {
Data Structures Lab Workbook (MCL507) |
106
2023--25
struct Deque dq;
initializeDeque(&dq);

enqueueRear(&dq, 10);
enqueueRear(&dq, 20);
enqueueFront(&dq, 5);
enqueueFront(&dq, 15);

peekFront(&dq);
peekRear(&dq);

dequeueFront(&dq);
dequeueRear(&dq);

peekFront(&dq);
peekRear(&dq);

return 0;
}

Output – Screenshots (Student Work Area):


Data Structures Lab Workbook (MCL507) |
107
2023--25

QUESTION BANK:

1. What are the applications of Doubly ended queues?


2. What is the complexity of all operations?
Data Structures Lab Workbook (MCL507) |
108
2023--25
Data Structures Lab Workbook (MCL507) |
109
2023--25
EXPERIMENT NO. 15

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with Non-linear data structure Binary Search Tree and its operations.

Outcome:

The students will be able to implement and use Binary Search Tree for solving various problems

Problem Statement:

Write a program to implement Following operations using Binary Search Tree:

1. Insertion
2. Deletion
3. Traversal [PREORDER, POSTORDER, INORDER]

Background:

Binary Search Tree is a node-based binary tree data structure which has the following properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.
Data Structures Lab Workbook (MCL507) |
110
2023--25

Insertion In Binary Search Tree:

1. Start from the root.


2. Compare the inserting element with root, if less than root, then recurse for left, else recurse for
right.
3. After reaching the end, just insert that node at left(if less than current) else right.

Deletion from Binary Search Tree:

1) Node to be deleted is the leaf: Simply remove from the tree.


50 50
/ \ delete(20) / \
30 70 ---------> 30 70
/ \ / \ \ / \
20 40 60 80 40 60 80
Data Structures Lab Workbook (MCL507) |
111
2023--25
2) Node to be deleted has only one child: Copy the child to the node and delete the child
50 50
/ \ delete(30) / \
30 70 ---------> 40 70
\ / \ / \
40 60 80 60 80
3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the
inorder successor to the node and delete the inorder successor. Note that inorder predecessor can
also be used.
50 60
/ \ delete(50) / \
40 70 ---------> 40 70
/ \ \
60 80 80

Algorithm (Student Work Area):

Insertion Algorithm:
1. Start at the root of the BST.
2. If the tree is empty, create a new node with the given key and set it as the root.
3. If the key to be inserted is smaller than the current node's key, move to the left subtree.
4. If the key to be inserted is greater than the current node's key, move to the right subtree.
5. Repeat steps 3-4 until a suitable position is found.
6. Insert the new node at the found position.
Deletion Algorithm:
1. Start at the root of the BST.
2. If the tree is empty, the key to be deleted is not in the tree.
3. If the key to be deleted is smaller than the current node's key, move to the left subtree.
4. If the key to be deleted is greater than the current node's key, move to the right subtree.
5. If the key to be deleted is equal to the current node's key, perform deletion: a. If the current
node has only one child or no child, remove the current node. b. If the current node has
two children, find the inorder successor (or predecessor) in the right (or left) subtree. c.
Replace the current node's key with the key of the successor (or predecessor). d. Delete the
successor (or predecessor) from the right (or left) subtree.
Data Structures Lab Workbook (MCL507) |
112
2023--25
6. Repeat steps 3-5 until the key is found and deleted.
Traversal Algorithms:
Inorder Traversal:
1. Traverse the left subtree in inorder.
2. Visit the current node.
3. Traverse the right subtree in inorder.
Preorder Traversal:
1. Visit the current node.
2. Traverse the left subtree in preorder.
3. Traverse the right subtree in preorder.
Postorder Traversal:
1. Traverse the left subtree in postorder.
2. Traverse the right subtree in postorder.
3. Visit the current node.

Code (Student Work Area):

#include <stdio.h>

#include <stdlib.h>

// Structure for a Node

struct Node {

int key;

struct Node *left, *right;

};
Data Structures Lab Workbook (MCL507) |
113
2023--25
// Function to create a new Node

struct Node* newNode(int key) {

struct Node* node = (struct Node*)malloc(sizeof(struct Node));

node->key = key;

node->left = node->right = NULL;

return node;

// Function to insert a key into BST

struct Node* insert(struct Node* root, int key) {

if (root == NULL)

return newNode(key);

if (key < root->key)

root->left = insert(root->left, key);

else if (key > root->key)

root->right = insert(root->right, key);

return root;

// Function to find the minimum value node in a BST

struct Node* minValueNode(struct Node* node) {

struct Node* current = node;


Data Structures Lab Workbook (MCL507) |
114
2023--25
while (current->left != NULL)

current = current->left;

return current;

// Function to delete a key from BST

struct Node* deleteNode(struct Node* root, int key) {

if (root == NULL)

return root;

if (key < root->key)

root->left = deleteNode(root->left, key);

else if (key > root->key)

root->right = deleteNode(root->right, key);

else {

if (root->left == NULL) {

struct Node* temp = root->right;

free(root);

return temp;

} else if (root->right == NULL) {

struct Node* temp = root->left;

free(root);

return temp;

}
Data Structures Lab Workbook (MCL507) |
115
2023--25

struct Node* temp = minValueNode(root->right);

root->key = temp->key;

root->right = deleteNode(root->right, temp->key);

return root;

// Function for inorder traversal

void inorderTraversal(struct Node* root) {

if (root != NULL) {

inorderTraversal(root->left);

printf("%d ", root->key);

inorderTraversal(root->right);

// Function for preorder traversal

void preorderTraversal(struct Node* root) {

if (root != NULL) {

printf("%d ", root->key);

preorderTraversal(root->left);

preorderTraversal(root->right);

}
Data Structures Lab Workbook (MCL507) |
116
2023--25
}

// Function for postorder traversal

void postorderTraversal(struct Node* root) {

if (root != NULL) {

postorderTraversal(root->left);

postorderTraversal(root->right);

printf("%d ", root->key);

// Driver program

int main() {

struct Node* root = NULL;

// Inserting elements into BST

root = insert(root, 50);

insert(root, 30);

insert(root, 20);

insert(root, 40);

insert(root, 70);

insert(root, 60);

insert(root, 80);
Data Structures Lab Workbook (MCL507) |
117
2023--25
// Inorder traversal

printf("Inorder traversal: ");

inorderTraversal(root);

printf("\n");

// Deleting an element

root = deleteNode(root, 20);

// Inorder traversal after deletion

printf("Inorder traversal after deletion: ");

inorderTraversal(root);

printf("\n");

// Preorder traversal

printf("Preorder traversal: ");

preorderTraversal(root);

printf("\n");

// Postorder traversal

printf("Postorder traversal: ");

postorderTraversal(root);

printf("\n");

return 0;
Data Structures Lab Workbook (MCL507) |
118
2023--25
}

Output – Screenshots (Student Work Area):

QUESTION BANK:

1. What is the difference between Binary Tree and Binary Search Tree?
2. What is the complexity of all search operations in BST?

EXPERIMENT NO. 16

Student Name and Roll Number:

Semester /Section:

Link to Code:

Date:

Faculty Signature:

Marks:

Objective(s):

To familiarize the students with different sorting operations.

Outcome:

The students will be able to implement and use various sorting techniques.

Problem Statement:

Write a program to implement:


Data Structures Lab Workbook (MCL507) |
119
2023--25
1. Bubble Sort
2. Insertions Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort

Background:

Sorting is the process of arranging the elements of an array so that they can be placed either in
ascending or descending order. For example, consider an array A = {A1, A2, A3, A4, …. An }, the
array is called to be in ascending order if element of A are arranged like A1 > A2 > A3 > A4 > A5
> .. > An .

Consider an array;

int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 )

After Sorting array would be:

A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 }

There are many techniques by using which, sorting can be performed.

S Sorting Description
N Algorithms

1 Bubble Sort It is the simplest sort method which performs sorting by repeatedly moving
the largest element to the highest index of the array. It comprises of
comparing each element to its adjacent element and replace them
accordingly.

2 Insertion Sort As the name suggests, insertion sort inserts each element of the array to its
proper place. It is a very simple sort method which is used to arrange the
deck of cards while playing bridge.

3 Merge Sort Merge sort follows divide and conquer approach in which, the list is first
divided into the sets of equal elements and then each half of the list is
Data Structures Lab Workbook (MCL507) |
120
2023--25

sorted by using merge sort. The sorted list is combined again to form an
elementary sorted array.

4 Quick Sort Quick sort is the most optimized sort algorithms which performs sorting in
O(n log n) comparisons. Like Merge sort, quick sort also work by using
divide and conquer approach.

5 Selection Sort Selection sort finds the smallest element in the array and place it on the
first place on the list, then it finds the second smallest element in the array
and place it on the second place. This process continues until all the
elements are moved to their correct ordering. It carries running time O(n2)
which is worst than insertion sort.

Algorithm (Student Work Area):

Bubble Sort:
1. Start from the beginning of the list.
2. Compare each pair of adjacent elements.
3. If they are in the wrong order, swap them.
4. Continue doing this for each pair until the end of the list is reached.
5. Repeat the process until the entire list is sorted.
Insertion Sort:
1. Start with the second element of the list.
2. Compare it with the elements before it and insert it into the correct position.
3. Move on to the next element and repeat the process.
4. Continue until the entire list is sorted.
Selection Sort:
1. Divide the list into a sorted and an unsorted region.
2. Find the smallest element in the unsorted region.
Data Structures Lab Workbook (MCL507) |
121
2023--25
3. Swap it with the first element of the unsorted region.
4. Expand the sorted region to include the newly sorted element.
5. Repeat the process until the entire list is sorted.
Quick Sort:
1. Choose a "pivot" element from the list.
2. Partition the list into two sublists - elements smaller than the pivot and elements greater
than the pivot.
3. Recursively apply the same process to each sublist.
4. Combine the sorted sublists to get the final sorted list.
Merge Sort:
1. Divide the list into two halves.
2. Recursively sort each half.
3. Merge the two sorted halves to create a new sorted list.
4. Continue this process until the entire list is sorted.

Code (Student Work Area):

1. Bubble sort
#include <stdio.h>

void swap(int *xp, int *yp) {


int temp = *xp;
*xp = *yp;
*yp = temp;
}

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
Data Structures Lab Workbook (MCL507) |
122
2023--25
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
2. Insertion Sort
#include <stdio.h>

void insertionSort(int arr[], int n) {


int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
3. Selection sort
#include <stdio.h>

void swap(int *xp, int *yp) {


int temp = *xp;
*xp = *yp;
Data Structures Lab Workbook (MCL507) |
123
2023--25
*yp = temp;
}

void selectionSort(int arr[], int n) {


int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
4. Quick sort
#include <stdio.h>

void swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = t;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
Data Structures Lab Workbook (MCL507) |
124
2023--25
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
5. Merge sort
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int l, int m, int r) {


int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

i = 0;
Data Structures Lab Workbook (MCL507) |
125
2023--25
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr) / sizeof(arr[0]);
Data Structures Lab Workbook (MCL507) |
126
2023--25

printf("Given array is \n");


for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


for (int i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
return 0;
}

Output – Screenshots (Student Work Area):


Data Structures Lab Workbook (MCL507) |
127
2023--25

QUESTION BANK:

Compare and contrast all Sorting techniques?

You might also like