DS Lab Manual
DS Lab Manual
DS Lab Manual
School of Engineering
Data Structure
Laboratory Manual
Department of Computer Science and Engineering
Data Structure
Name:
University Serial
Number:
Vision and Mission of the University
Vision
To be a Centre of excellence in education, research & training, innovation & entrepreneurship
and to produce citizens with exceptional leadership qualities to serve national and global needs.
Mission
To achieve our objectives in an environment that enhances creativity, innovation and scholarly
pursuits while adhering to our vision.
Values
• The values that drive DSU and support its vision: The Pursuit of Excellence
• A commitment to strive continuously to improve ourselves and our systems with the aim of
becoming the best in our field.
Fairness
A commitment to objectivity and impartiality, to earn the trust and respect of society.
Leadership
A commitment to lead responsively and creatively in educational and research processes.
Vision
To develop pool of high calibre professionals, researchers and entrepreneurs in the areas of
Computer Science & Engineering and Information Technology with exceptional technical
expertise, skills and ethical values, capable of providing innovative solutions to the national
and global needs.
Mission
• To create a robust ecosystem where academicians, concept developers, product designers,
business incubators, product developers, entrepreneurs, mentors and financial institutions
are brought together under one platform of the department.
• To establish Project Environment in the Department with open source tools, provide hands-
on experience to students by establishing a process to channelize their effort towards
acquiring relevant competencies and skills in their chosen technology areas and domains.
• To create continuous learning environment for faculty and establish Research Centres in
collaboration with Industries and Institutions of National/International repute and conduct
research in emerging areas as well as socially relevant technical and domain areas through
funded research projects.
Program Educational Objectives (PEO's)
PEO1: Engage in the design, development, testing/verification and validation, and operation
of computational systems in the field of Information Technology and related areas, or in
multidisciplinary teams in any field where computing can be applied.
PEO2: Solve problems of social relevance applying the knowledge of Computer Science
Engineering and/or pursue higher education and
research.
PEO4: Engage in lifelong, self-directed learning and career enhancement, anticipate changing
professional and societal needs, and adapt rapidly to these changing needs.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO4: Conduct investigations of complex problems: Use research- based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
PSO2: Find and articulate digital and intelligent solution that can fully or partially automate
various aspects of human activity.
Dayananda Sagar University
Laboratory Certificate
experiments in Data Structure Laboratory prescribed by the University for the 3rd semester
Date:___________________
Marks
Maximum Obtained
Index
Experiment 1
Program
#include <stdio.h>
int main()
{
int n;
printf("Enter the size of the array:");
scanf("%d",&n);
int arr[n];
Sample Output
Enter the size of the array: 4
Enter the 4 values to store it in array: 1
2
3
4
The values stored in the array are:
1
2
3
4
Rules to check.
i. First two positions of an array must be a State Code.
ii. Next two positions of an array must be District Code.
iii. Next two Positions of an array must be a Serial Number of an RTO.
iv. Penultimate r positions of an array must be a vehicle number.
Program
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Function to verify if a vehicle registration number is valid
bool verifyRegistration(char registration[])
{
// Check if the registration number has exactly 10 characters
if (strlen(registration) != 10)
{
return false;
}
// Check if the first two characters are alphabets (e.g., "KA" for Karnataka)
for (int i = 0; i < 2; i++)
{
if (!isalpha(registration[i]))
{
return false;
}
}
// Check if the next two characters are numbers (e.g., "09" for a specific district)
for (int i = 2; i < 4; i++)
{
if (!isdigit(registration[i]))
{
return false;
}
}
// Check if the next two characters are alphabets (e.g., "MN" for serial number)
for (int i = 4; i < 6; i++)
// Check if the penultimate two characters are numbers (e.g., "3865" for vehicle number)
for (int i = 6; i < 10; i++)
{
if (!isdigit(registration[i]))
{
return false;
}
}
return true;
}
int main() {
char registration[11];
printf("Enter a vehicle registration number: ");
scanf("%s", registration);
if (verifyRegistration(registration))
{
printf("Accept: Vehicle registration number is valid.\n");
}
else
{
printf("Reject: Vehicle registration number is invalid.\n");
}
return 0;
}
Sample Output
Enter a vehicle registration number: KA09MN3865
Accept: Vehicle registration number is valid.
Experiment 2
2. a. Write a C program that multiplies two matrices, ensuring that the number of columns in
the first matrix is equal to the number of rows in the second matrix. Display the resulting
matrix. Note: Prompt user to enter the size of the matrix.
Program
#include <stdio.h>
int main() {
int m, n, p, q;
printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &m, &n);
printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &p, &q);
if (n != p) {
printf("Matrix multiplication is not possible. Column of the first matrix must be equal to
the row of the second matrix.\n");
return 1;
}
// Matrix multiplication
for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
resultMatrix[i][j] = 0;
for (int k = 0; k < n; k++) {
return 0;
}
Conditions to check
i. Every row should encompass the numbers 1 through 9, ensuring no duplication.
ii. Each column should consist of the numbers 1 to 9, ensuring no duplication.
iii. Within the nine 3x3 sub-boxes of the grid, no repetitions allowed.
Sample Input
//copy and paste the input
int sudoku[9][9] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
Sample Output
Accept
#include <stdio.h>
int isValidSudoku(int board[9][9]) {
// Check rows
for (int i = 0; i < 9; i++) {
int row[10] = {0};
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0 && row[board[i][j]] == 1) {
return 0; // Invalid Sudoku
}
row[board[i][j]] = 1;
}
}
// Check columns
for (int j = 0; j < 9; j++) {
int col[10] = {0};
for (int i = 0; i < 9; i++) {
if (board[i][j] != 0 && col[board[i][j]] == 1) {
return 0; // Invalid Sudoku
}
int main() {
int sudoku[9][9] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (isValidSudoku(sudoku)) {
printf("Valid Sudoku\n");
} else {
printf("Invalid Sudoku\n");
}
return 0;
}
Experiment 3
3. a. A school wants to develop a student academic system to track student progress and
generate reports for teachers and parents. The system should store the following information
for each student: Student ID, Name, Grade, Subject, Marks. The system should also be able to
do the following operations:
i. Calculate the average marks for each student.
ii. Assign grades based on the average marks.
Conditions
i. Must use array of structures.
ii. Use simple structure variable to access the members of the structure.
ii. Enter marks for minimum of 5 students with subjects each.
Program
#include <stdio.h>
int main()
{
struct Student students[5];
return 0;
}
Conditions
i. Must use array of structures.
ii. Use pointer to structure to access the members of the structure.
ii. Enter marks for minimum of 5 students with subjects each.
Instructions to Faculties
If needed, please take extra lab hours in subsequent week to complete this experiment in detail.
The concepts discussed in this experiment will make solid foundation for the forthcoming
experiments namely (stack using linked list, queue using linked list, singly linked list, doubly
linked list, circular linked list).
Program
#include <stdio.h>
int main()
{
struct Student students[5];
struct Student *studentPtr = students;
return 0;
}
Experiment 4
4. a. Write a C program to create a stack data structure using a linked list instead of an array
and implement push, pop and isEmpty operations accordingly.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
struct Stack* stack = createStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);
return 0;
}
Operations
i. Visit a URL (push)
ii. Go Back (pop)
iii. Display Current URL
i. Visit a URL: The program prompts the user to enter the URL (Uniform Resource Locator)
they want to visit. The user enters the web address (e.g., "https://www.example.com") or a
specific webpage URL. After the user provides the URL, the program creates a new node
containing this URL and pushes it onto the stack. This action simulates the user's movement to
a new web page. Additionally check if the stack overflow condition for insertion.
ii. Navigating Backward: In your C program for the web browser history tracker, ensure that
users can navigate backward through their browsing history by popping URLs from the stack
and displaying the current URL. Provide a mechanism for handling the case when there are no
more URLs to go back to.
iii. Displaying Current URL: In your web browser history tracker program, create a function
that displays the current URL that the user is on. Ensure that it correctly reflects the URL on
the top of the stack.
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_URL_LENGTH 100
int main() {
Stack historyStack;
initialize(&historyStack);
int choice;
char url[MAX_URL_LENGTH];
while (1) {
printf("\nMenu:\n");
printf("1. Visit a URL\n");
printf("2. Go Back\n");
printf("3. Display Current URL\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
return 0;
}
Sample Output
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 1
Enter URL to visit: example.com
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 1
Enter URL to visit: Meow
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 2
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 3
Current URL: example.com
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 2
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 3
No URL currently loaded.
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 2
No more URLs in the history.
Menu:
1. Visit a URL
2. Go Back
3. Display Current URL
4. Exit
Enter your choice: 4
Experiment 5
5. a. Write a C program to implement a queue data structure using a singly linked list. Your
program should provide the following functionalities:
You need to define suitable functions to perform these operations and demonstrate their usage
in your program. Ensure that you handle edge cases such as queue underflow (when trying to
dequeue from an empty queue).
Program
#include <stdio.h>
#include <stdlib.h>
if (isEmpty(queue))
{
queue->front = queue->rear = newNode;
} else
{
queue->rear->next = newNode;
queue->rear = newNode;
}
}
free(temp);
return data;
}
printf("\n");
}
int main()
{
struct Queue* queue = createQueue();
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
display(queue);
display(queue);
return 0;
}
Program
#include <stdio.h>
#include <stdlib.h>
// Initialize a queue
struct Queue* createQueue()
{
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
return queue;
}
if (isEmpty(queue)) {
queue->front = queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
if (isEmpty(queue))
{
return emptyCustomer; // Queue is empty
}
free(temp);
return customer;
}
int main()
{
// Total number of tickets available
int totalTickets = 100;
struct Queue* ticketQueue = createQueue();
printf("Do you want to add another customer? (1 for yes, 0 for no): ");
int choice;
scanf("%d", &choice);
if (choice != 1)
{
break;
}
}
return 0;
}
Experiment 6
6. a. Write a C program to implement a singly linked list. The program should allow the user
to perform the following operations:
Additionally, ensure that you handle edge cases gracefully, such as an empty list or attempting
to delete a node that does not exist.
Program
#include <stdio.h>
#include <stdlib.h>
newNode->data = value;
newNode->next = head;
return newNode;
}
if (head == NULL) {
return newNode;
}
return head;
}
if (head->data == value) {
struct Node* temp = head;
head = head->next;
free(temp);
return head;
}
if (current->next == NULL) {
printf("Value not found in the list. Cannot delete.\n");
return head;
}
return head;
}
int main() {
struct Node* head = NULL;
int choice, value;
while (1) {
printf("\nMenu:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Delete by value\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter a value to insert: ");
scanf("%d", &value);
head = insertAtBeginning(head, value);
break;
case 2:
printf("Enter a value to insert: ");
scanf("%d", &value);
head = insertAtEnd(head, value);
break;
case 3:
printf("Enter a value to delete: ");
scanf("%d", &value);
head = deleteByValue(head, value);
break;
case 4:
displayList(head);
break;
case 5:
// Clean up and exit
while (head != NULL) {
struct Node* temp = head;
head = head->next;
free(temp);
}
return 0;
}
Task: Your task is to swap every two adjacent nodes in the list and return the new head of the
modified list. In other words, you need to rearrange the nodes so that the linked list now looks
like 2 -> 1 -> 4 -> 3 -> 5.
Constraints:
You are not allowed to modify the values in the nodes. Only the nodes themselves may be
changed. If the number of nodes in the linked list is odd, the last node should remain in its
original position.
Sample Output
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 2 -> 1 -> 4 -> 3 -> 5
Program
#include <stdio.h>
#include <stdlib.h>
if (current != NULL) {
nextNode = current->next;
}
}
return head;
}
int main() {
// Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
struct ListNode* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
// Clean up memory
while (head != NULL) {
struct ListNode* temp = head;
head = head->next;
free(temp);
}
return 0;
}
Experiment 7
7. a. Write a C program to implement a doubly linked list data structure from scratch. The
program should provide the following functionalities:
You need to define suitable functions to perform these operations and demonstrate their usage
in your program. Ensure that you handle edge cases, such as deleting a node that doesn't exist
in the list or displaying an empty list.
Program
#include <stdio.h>
#include <stdlib.h>
if (list->head != NULL)
{
list->head->prev = newNode;
}
list->head = newNode;
}
if (list->head == NULL)
{
list->head = newNode;
return;
}
current->next = newNode;
newNode->prev = current;
}
if (position == 0)
{
insertAtBeginning(list, data);
return;
Data Structure Laboratory Manual
Department of Computer Science and Engineering, Dayananda Sagar University, Bengaluru,
Karnataka.
}
if (current == NULL)
{
printf("Position out of range.\n");
free(newNode);
return;
}
newNode->prev = current->prev;
newNode->next = current;
if (current->prev != NULL)
{
current->prev->next = newNode;
}
else
{
list->head = newNode;
}
current->prev = newNode;
}
if (current->next != NULL)
{
current->next->prev = current->prev;
}
free(current);
return;
}
current = current->next;
}
if (current == NULL)
{
printf("The list is empty.\n");
return;
}
int main()
{
struct DoublyLinkedList myList;
initializeList(&myList);
insertAtBeginning(&myList, 10);
insertAtEnd(&myList, 20);
insertAtPosition(&myList, 15, 1);
deleteNode(&myList, 20);
displayList(&myList);
return 0;
}
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (cart->tail != NULL)
{
cart->tail->next = newItem;
}
cart->tail = newItem;
if (cart->head == NULL)
{
cart->head = newItem;
}
}
if (current->next != NULL)
{
current->next->prev = current->prev;
}
else
{
cart->tail = current->prev;
}
free(current);
return;
}
printf("Shopping Cart:\n");
while (current != NULL)
{
printf("Name: %s, Price: $%.2f, Quantity: %d, Total Cost: $%.2f\n", current->name,
current->price, current->quantity, current->price * current->quantity);
current = current->next;
}
printf("\n");
}
// Function to calculate and display the total cost of items in the cart
void displayTotalCost(struct ShoppingCart* cart)
{
struct CartItem* current = cart->head;
float totalCost = 0.0;
int main()
{
struct ShoppingCart myCart;
initializeCart(&myCart);
return 0;
}
Experiment 8
8. a. Write a C program to create a circular queue using a circular linked list data structure.
Your program should support the following operations:
Ensure that your circular queue maintains its circular behavior, meaning that enqueuing
elements beyond the queue's capacity should wrap around to the beginning. Additionally,
handle cases when the queue is empty or full gracefully.
Program
#include <stdio.h>
#include <stdlib.h>
if (isEmpty(queue)) {
// If the queue is empty, set both front and rear to the new node
queue->front = newNode;
queue->rear = newNode;
newNode->next = newNode; // Circular link to itself
} else {
// Link the new node to the rear and update the rear
newNode->next = queue->front; // Circular link
queue->rear->next = newNode;
queue->rear = newNode;
}
}
int removedValue;
struct QueueNode* temp = queue->front;
if (queue->front == queue->rear) {
// If there is only one element in the queue
removedValue = temp->data;
queue->front = NULL;
queue->rear = NULL;
free(temp);
} else {
// Remove and update the front of the queue
removedValue = temp->data;
queue->front = temp->next;
queue->rear->next = queue->front; // Circular link
free(temp);
}
int main() {
struct CircularQueue* queue = createCircularQueue();
int choice, value;
while (1) {
printf("\nMenu:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter a value to enqueue: ");
scanf("%d", &value);
enqueue(queue, value);
break;
case 2:
value = dequeue(queue);
if (value != -1) {
printf("Dequeued value: %d\n", value);
}
break;
case 3:
displayQueue(queue);
break;
case 4:
// Clean up and exit
return 0;
}
Operations
i. Add a Song
ii. Skip to Next Song
iii. Remove Currently Playing Song
iv. Display Currently Playing Song
v. Display Playlist
Add a Song: Allow users to add songs to the playlist. Each song has a title and artist name.
New songs should be added to the end of the playlist.
Skip to Next Song: Implement an option for users to skip to the next song in the playlist. If the
current song is the last one, the program should loop back to the first song.
Remove Currently Playing Song: Users should be able to remove the currently playing song
from the playlist. After removal, the program should automatically start playing the next song.
Ensure that your program utilizes a circular linked list data structure to manage the playlist and
maintains the circular behavior, allowing continuous music playback. Your program should
display the playlist's current status and give users a menu to choose the above options.
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (playlist == NULL) {
playlist = newSong;
playlist->next = playlist; // Circular link to itself
} else {
struct Song* current = playlist;
while (current->next != playlist) {
current = current->next;
}
current->next = newSong;
newSong->next = playlist;
}
return playlist;
}
if (playlist->next == playlist) {
// Only one song in the playlist
free(playlist);
return NULL;
}
return playlist;
}
int main() {
struct Song* playlist = NULL;
int choice;
char title[100], artist[100];
while (1) {
printf("\nMenu:\n");
printf("1. Add a Song\n");
printf("2. Skip to Next Song\n");
printf("3. Remove Currently Playing Song\n");
printf("4. Display Currently Playing Song\n");
printf("5. Display Playlist\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
return 0;
}
Experiment 9
Program
#include <stdio.h>
#include <stdlib.h>
return root;
}
return root->data;
}
return root->data;
}
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
displayInorder(root->left);
printf("%d ", root->data);
displayInorder(root->right);
}
Data Structure Laboratory Manual
Department of Computer Science and Engineering, Dayananda Sagar University, Bengaluru,
Karnataka.
int main()
{
struct Node* root = initializeBST();
while (1)
{
printf("\nBinary Search Tree Menu:\n");
printf("1. Insert a node\n");
printf("2. Delete a node\n");
printf("3. Find Minimum\n");
printf("4. Find Maximum\n");
printf("5. Display Inorder Traversal\n");
printf("6. Exit\n");
switch (choice)
{
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insertNode(root, value);
break;
case 2:
printf("Enter value to delete: ");
scanf("%d", &value);
root = deleteNode(root, value);
break;
case 3:
printf("Minimum value: %d\n", findMinimum(root));
break;
case 4:
printf("Maximum value: %d\n", findMaximum(root));
break;
case 5:
printf("Inorder Traversal: ");
displayInorder(root);
printf("\n");
break;
case 6:
exit(0);
Data Structure Laboratory Manual
Department of Computer Science and Engineering, Dayananda Sagar University, Bengaluru,
Karnataka.
default:
printf("Invalid choice. Try again.\n");
break;
}
}
return 0;
}
Instructions
1. The questions may be distributed at the start of the semester.
2. Students are encouraged to employ various data structure programming concepts to address
the open-ended questions.
3. It is expected that students will solve and submit their solutions to the faculty members
responsible for the course only after the conclusion of the second mid-semester exam.
Questions
1. A man in an automobile search for another man who is located at some point of a certain
road. He starts at a given point and knows in advance the probability that the second man is at
any given point of the road. Since the man being sought might be in either direction from the
starting point, the searcher will, in general, must turn around many times before finding his
target. How does he search to minimize the expected distance travelled? When can this
minimum expectation be achieved?
2. The computing resources of a cloud are pooled and allocated according to customer
demand. This has led to increased use of energy on the part of the service providers due to the
need to maintain the computing infrastructure. What data structure will you use for allocating
resources which addresses the issue of energy saving? Why? Design the solution.