LAB MANUAL
OF
DATA STRUCTURE LABORATORY
(UGCA1918)
COURSE: BCA / B.SC
SEMESTER: 3RD
FACULTY: MR. SACHIN YADAV
SESSION: JULY – DEC, 2025
Prepared By – Mr. Sachin Yadav
List of Experiments
S. No. Experiments
1 Program for using Dynamic Functions (malloc(), calloc(), realloc() and free()) functions.
2 Program to insert, delete and traverse an element from an array
3 Program to merge one dimensional arrays
4 Program for addition and subtraction of two matrices.
5 Program for implementing multiplication of two matrices
6 Implement linear search using one- and two-dimensional array.
7 Program for implementing selection sort.
8 Program for implementing insertion sort.
9 Program for implementing quick sort.
10 Program for implementing merge sort.
11 Program to calculate length of the string using user defined function.
12 Program to concatenate and compare two strings using user defined function.
13 Program for using the concept of pointer to string.
14 Program to reverse a sentence by recursion.
15 Program to delete all repeated words in string.
16 Program to find the number of vowels, consonants, digits and white space in a string.
17 Program to find the length of the longest repeating sequence in a string.
18 Program to find highest and lowest frequency character in a string.
19 Program for implementing Stack using array.
20 Program for implementing Stack using pointer.
21 Program for implementing multiple stack.
22 Program for converting infix to postfix form.
23 Program for implementing Queue using array.
24 Program for dynamic implementation of queue.
25 Program for implementing circular queue.
26 Program for implementing dequeue.
27 Program for implementing priority queue.
28 Program for implementing Singly Linked list.
29 Program for implementing Doubly Linked list.
30 Program for implementing Binary Search Tree.
31 Program for Breadth First Search (BFS) for graph traversal.
32 Program for Depth First Search (DFS) for graph traversal.
Prepared By – Mr. Sachin Yadav
Lab Lecture Plan
Course: BCA Semester: 3rd
Subject: Data Structure Subject Code: UGCA1918
Lecture. CO’s
Topic to be covered Proposed Actual
No Attained Remarks
Dates Dates
Program for using Dynamic Functions (malloc(),
1 CO1
calloc(), realloc() and free()) functions. 04-08-2025
Program to insert, delete and traverse an element
2 CO1
from an array 05-08-2025
3 Program to merge one dimensional arrays CO1
07-08-2025
Program for addition and subtraction of two
4 CO1
matrices. 08-08-2025
Program for implementing multiplication of two
5 CO1
matrices 11-08-2025
Implement linear search using one- and two-
6 CO1, CO4
dimensional array. 12-08-2025
7 Program for implementing selection sort. CO2
14-08-2025
8 Program for implementing insertion sort. CO2
18-08-2025
9 Program for implementing quick sort. CO2
19-08-2025
10 Program for implementing merge sort. CO2
21-08-2025
Program to calculate length of the string using user
11 CO2
defined function. 22-08-2025
Program to concatenate and compare two strings
12 CO2
using user defined function. 23-08-2025
13 Program for using the concept of pointer to string. CO2
25-08-2025
14 Program to reverse a sentence by recursion. CO2
26-08-2025
15 Program to delete all repeated words in string. CO2
28-08-2025
Program to find the number of vowels, consonants,
16 CO2
digits and white space in a string. 29-08-2025
Program to find the length of the longest repeating
17 CO2
sequence in a string. 01-09-2025
Prepared By – Mr. Sachin Yadav
Program to find highest and lowest frequency
18 CO2
character in a string. 02-09-2025
19 Program for implementing Stack using array. CO3
04-09-2025
20 Program for implementing Stack using pointer. CO3
05-09-2025
21 Program for implementing multiple stack. CO3
08-09-2025
22 Program for converting infix to postfix form. CO3
09-09-2025
23 Program for implementing Queue using array. CO3
11-09-2025
24 Program for dynamic implementation of queue. CO3
12-09-2025
25 Program for implementing circular queue. CO3
15-09-2025
26 Program for implementing dequeue. CO3
16-09-2025
27 Program for implementing priority queue. CO3
18-09-2025
28 Program for implementing Singly Linked list. CO4
19-09-2025
29 Program for implementing Doubly Linked list. CO4
29-09-2025
30 Program for implementing Binary Search Tree. CO4
30-09-2025
Program for Breadth First Search (BFS) for graph
31 CO4
traversal. 03-10-2025
Program for Depth First Search (DFS) for graph
32 CO4
traversal. 03-10-2025
Prepared By – Mr. Sachin Yadav
Experiment – 01
AIM: Program for using Dynamic Functions (malloc(), calloc(), realloc() and free())
Objective:
In C, dynamic memory allocation allows us to allocate memory at runtime using special functions. These
functions are defined in the stdlib.h header and allow flexible use of memory based on user requirements.
Software & Hardware Required:
• Software: Any C compiler (GCC, Turbo C, Code::Blocks, Dev C++)
• Hardware: A basic system with at least 2GB RAM
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int i;
// malloc
ptr = (int *)malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("malloc failed.\n");
return 1;
}
printf("Using malloc:\n");
for (i = 0; i < 5; i++) {
ptr[i] = i + 1;
printf("%d ", ptr[i]);
}
printf("\n");
free(ptr); // releasing malloc-ed memory
// calloc
ptr = (int *)calloc(5, sizeof(int));
if (ptr == NULL) {
Prepared By – Mr. Sachin Yadav
printf("calloc failed.\n");
return 1;
}
printf("Using calloc:\n");
for (i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
// realloc
ptr = (int *)realloc(ptr, 8 * sizeof(int));
if (ptr == NULL) {
printf("realloc failed.\n");
return 1;
}
printf("Using realloc:\n");
for (i = 0; i < 8; i++) {
ptr[i] = i + 10;
printf("%d ", ptr[i]);
}
printf("\n");
// free
free(ptr);
printf("Memory freed successfully.\n");
return 0;
}
Viva Questions:
• What is the difference between malloc() and calloc()?
• Why do we use free() in C programs?
• What happens if we don’t free allocated memory?
• Can we use realloc() without malloc() or calloc()?
• What is a memory leak?
Prepared By – Mr. Sachin Yadav
Experiment – 02
AIM: Program to Insert, Delete, and Traverse an Element from an Array (in Python)
Objective: Arrays are a fundamental data structure used to store elements of the same type. In Python, the
list data type can be used as a dynamic array. We can insert, delete, and access elements easily using built-
in methods.
Software & Hardware Required:
• Software: Python 3.x
• Hardware: Basic computer with Python installed
Code:
# Initial array
arr = [10, 20, 30, 40, 50]
print("Initial Array:")
print(arr)
# Traversing the array
print("\nTraversing the array:")
for i in arr:
print(i, end=' ')
print()
# Inserting element at index 2
arr.insert(2, 25)
print("\nArray after inserting 25 at index 2:")
print(arr)
Prepared By – Mr. Sachin Yadav
# Deleting element at index 3
deleted_element = arr.pop(3)
print(f"\nArray after deleting element at index 3 (deleted: {deleted_element}):")
print(arr)
# Deleting a specific value, e.g., 50
if 50 in arr:
arr.remove(50)
print("\nArray after deleting value 50:")
print(arr)
else:
print("\nValue 50 not found in the array.")
Outcome:
The program demonstrates how to:
• Traverse all array elements
• Insert a new element at a given index
• Delete an element using index and value
Viva Questions:
1. What is an array?
2. How do you insert an element at a specific index in Python?
3. What is the difference between remove() and pop()?
4. What happens if you use pop() with an index that doesn't exist?
5. Can you store different data types in a Python list?
Prepared By – Mr. Sachin Yadav
Experiment – 03
AIM: Program to Merge One Dimensional Arrays (in Python)
Objective: Merging arrays is a common operation in programming where two or more sequences are
combined into one. In Python, we use lists to represent arrays, and merging can be done using the +
operator or by using a loop.
Software & Hardware Required:
• Software: Python 3.x
• Hardware: A system capable of running basic Python code
Code:
# Two 1D arrays
array1 = [1, 3, 5, 7]
array2 = [2, 4, 6, 8]
# Merging arrays using '+' operator
merged_array = array1 + array2
# Display results
print("First Array:", array1)
print("Second Array:", array2)
print("Merged Array:", merged_array)
Outcome: The program successfully merges two one-dimensional arrays into a single array.
Viva Questions:
1. What is a one-dimensional array?
2. How can two arrays be merged in Python?
3. What is the difference between + and extend() in Python lists?
4. Can we merge arrays of different lengths?
5. What data types can Python lists contain?
Prepared By – Mr. Sachin Yadav
Experiment - 04
AIM: Program for Addition and Subtraction of Two Matrics (in Python)
Objective: A matrix is a 2-dimensional array arranged in rows and columns. In mathematical operations,
two matrices can be added or subtracted if they have the same dimensions.
Software & Hardware Required:
• Software: Python 3.x
• Hardware: Computer with a Python environment
Code:
# Define two 2x2 matrices
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
# Initialize result matrices
sum_matrix = [[0, 0], [0, 0]]
diff_matrix = [[0, 0], [0, 0]]
# Perform addition and subtraction
for i in range(2):
for j in range(2):
sum_matrix[i][j] = matrix1[i][j] + matrix2[i][j]
diff_matrix[i][j] = matrix1[i][j] - matrix2[i][j]
# Print results
print("Matrix 1:")
for row in matrix1:
print(row)
print("\nMatrix 2:")
for row in matrix2:
Prepared By – Mr. Sachin Yadav
print(row)
print("\nSum of Matrices:")
for row in sum_matrix:
print(row)
print("\nDifference of Matrices:")
for row in diff_matrix:
print(row)
Outcome: The program successfully performs addition and subtraction of two matrices and displays the
results in matrix form.
Viva Questions:
1. What is a matrix?
2. Can we add matrices of different sizes?
3. How is matrix addition different from matrix multiplication?
4. What is the time complexity of matrix addition?
5. How do you represent a 2D matrix in Python?
Prepared By – Mr. Sachin Yadav
Experiment – 05
AIM: Program for Matrix Multiplication (in Python)
Objective: Matrix multiplication is a fundamental operation in mathematics and computer science.
Two matrices can be multiplied if the number of columns in the first matrix equals the number of rows in
the second matrix.
Software & Hardware Required:
• Software: Python 3.x
• Hardware: A basic computer with Python installed
Code:
# Define matrices
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# Initialize result matrix with zeros
result = [[0, 0], [0, 0]]
# Multiply matrices
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
# Print matrices and result
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
Prepared By – Mr. Sachin Yadav
for row in B:
print(row)
print("\nProduct of A and B:")
for row in result:
print(row)
Outcome: The program multiplies two 2x2 matrices and displays the result in matrix form.
Viva Questions:
1. What are the conditions for matrix multiplication?
2. What is the time complexity of matrix multiplication?
3. Can matrix multiplication be commutative?
4. How do you represent a matrix in Python?
5. What is the dimension of the result if matrix A is 2×3 and B is 3×2?
Prepared By – Mr. Sachin Yadav
Experiment - 06
AIM: Program to Search an Element from Array (in Python)
Objective: Searching is a common operation where we look for a particular value in a data structure. In
Python, the list data type supports several ways to search for elements using built-in functions or manual
iteration.
Software & Hardware Required:
• Software: Python 3.x
• Hardware: A basic system with Python installed
Code:
# Define the array
arr = [10, 20, 30, 40, 50]
# Element to search
search_element = int(input("Enter the element to search: "))
# Perform linear search
found = False
for i in range(len(arr)):
if arr[i] == search_element:
print(f"Element {search_element} found at index {i}")
found = True
break
if not found:
print(f"Element {search_element} not found in the array.")
Outcome: The program successfully searches and identifies the position of an element in the array if it
exists.
Viva Questions:
• What is linear search?
• What is the time complexity of linear search?
• Can binary search be used on unsorted arrays?
• How do you check if an element exists in a list using Python?
• What happens if .index() is used and the element is not found?
Prepared By – Mr. Sachin Yadav
Experiment - 07
Aim: Write a Python program to sort an array using Selection Sort.
S/W & H/W Required: Python 3.x, basic computer.
Code [python]:
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print("Sorted array:", arr)
Output: Sorted array: [11, 12, 22, 25, 64]
Viva Questions:
1. What is the time complexity of selection sort?
2. Is it stable?
3. How is it different from bubble sort?
Prepared By – Mr. Sachin Yadav
Experiment - 08
Aim: To write a program that implements insertion sort.
S/W & H/W Required: Python 3.x, basic computer.
Code [python]:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array:", arr)
Output: Sorted array: [5, 6, 11, 12, 13]
Viva Questions:
1. Best case for insertion sort?
2. When is it better than selection sort?
3. Is insertion sort stable?
Prepared By – Mr. Sachin Yadav
Experiment - 9
Aim: Sort an array using the divide-and-conquer strategy (quick sort).
S/W & H/W Required: Python 3.x, basic computer.
Code [python]:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
arr = [10, 7, 8, 9, 1, 5]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
Output: Sorted array: [1, 5, 7, 8, 9, 10]
Viva Questions:
1. What is the average time complexity of quick sort?
2. Is quick sort stable?
3. What is the worst case?
Prepared By – Mr. Sachin Yadav
Experiment - 10
Aim: To write a program that uses the divide and conquer method to sort an array.
S/W & H/W Required: Python 3.x, basic computer.
Code [python]:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
Prepared By – Mr. Sachin Yadav
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
arr = [12, 11, 13, 5, 6, 7]
merge_sort(arr)
print("Sorted array:", arr)
Output: Sorted array: [5, 6, 7, 11, 12, 13]
Viva Questions:
1. What is merge sort?
2. Is it stable?
3. What is its space complexity?
Prepared By – Mr. Sachin Yadav
Experiment - 11
Aim: Program to calculate length of the string using user defined function
S/W & H/W Required:
Software: Python 3.x
Hardware: Any basic system with Python installed
Code [python]:
def string_length(s):
count = 0
for char in s:
count += 1
return count
# Input from user
user_string = input("Enter a string: ")
length = string_length(user_string)
print("Length of the string:", length)
Sample Output:
Enter a string: Hello World
Length of the string: 11
Viva Questions:
1. How does Python store a string?
2. What is a user-defined function?
3. How can you calculate string length without using len()?
4. What is the time complexity of this function?
5. What would happen if you used len() instead?
Prepared By – Mr. Sachin Yadav
Experiment - 12
Aim: Concatenate and Compare Two Strings Using User Defined Function
S/W & H/W Required:
Python 3.x, standard computer
Code [python]:
def my_concat(str1, str2):
result = ''
for ch in str1:
result += ch
for ch in str2:
result += ch
return result
def my_compare(str1, str2):
if len(str1) != len(str2):
return False
for i in range(len(str1)):
if str1[i] != str2[i]:
return False
return True
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
concat_result = my_concat(s1, s2)
compare_result = my_compare(s1, s2)
print("Concatenated String:", concat_result)
print("Strings are Equal:" if compare_result else "Strings are Not Equal")
Prepared By – Mr. Sachin Yadav
Sample Output:
Enter first string: Hello
Enter second string: World
Concatenated String: HelloWorld
Strings are Not Equal
Viva Questions:
1. How can you concatenate two strings without +?
2. What is the difference between == and is?
3. What is lexicographical order?
Prepared By – Mr. Sachin Yadav
Experiment - 13
Aim: Using the Concept of Pointer to String
S/W & H/W Required:
Python 3.x, standard computer
Code [python]:
def print_string_reference(string_ref):
print("String via reference:", string_ref)
original_string = "CodeBuzz"
ref_string = original_string # behaves like a pointer reference
print_string_reference(ref_string)
Output:
String via reference: CodeBuzz
Viva Questions:
1. Do pointers exist in Python?
2. What is the difference between mutable and immutable?
3. Is string mutable in Python?
Prepared By – Mr. Sachin Yadav
Experiment – 14
Aim: To write a recursive function to reverse a sentence in Python.
S/W & H/W Required: Python 3.x, standard computer
Code [python]:
def reverse_sentence(sentence):
if len(sentence) == 0:
return ""
else:
return reverse_sentence(sentence[1:]) + sentence[0]
user_input = input("Enter a sentence: ")
reversed_str = reverse_sentence(user_input)
print("Reversed Sentence:", reversed_str)
Sample Output:
Enter a sentence: Hello World
Reversed Sentence: dlroW olleH
Viva Questions:
1. What is recursion?
2. Define base case and recursive case.
3. What is stack overflow in recursion?
Prepared By – Mr. Sachin Yadav
Experiment- 15
Aim: Delete All Repeated Words in String
S/W & H/W Required: Python 3.x, basic IDE
Code [python]:
def remove_duplicates(sentence):
words = sentence.split()
seen = set()
result = []
for word in words:
if word not in seen:
result.append(word)
seen.add(word)
return ' '.join(result)
text = input("Enter a sentence: ")
print("Without repeated words:", remove_duplicates(text))
Sample Output:
Input: this is a test this is only a test
Output: this is a test only
Viva Questions:
• What data structure helps remove duplicates?
• What is a set in Python?
Prepared By – Mr. Sachin Yadav
Experiment - 16
Aim: Find Number of Vowels, Consonants, Digits & Spaces
S/W & H/W Required: Python 3.x
Code [python]:
def analyze_string(s):
vowels = "aeiouAEIOU"
v=c=d=w=0
for ch in s:
if ch in vowels:
v += 1
elif ch.isalpha():
c += 1
elif ch.isdigit():
d += 1
elif ch.isspace():
w += 1
return v, c, d, w
s = input("Enter a string: ")
v, c, d, w = analyze_string(s)
print("Vowels:", v, "Consonants:", c, "Digits:", d, "Whitespaces:", w)
Viva Questions:
• How are characters classified in Python?
• Difference between isalpha() and isnumeric()?
Prepared By – Mr. Sachin Yadav
Program 17: Longest Repeating Sequence in String
S/W & H/W Required: Python 3.x
Code [python]:
def longest_repeating_sequence(s):
max_len = 1
curr_len = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
curr_len += 1
max_len = max(max_len, curr_len)
else:
curr_len = 1
return max_len
s = input("Enter a string: ")
print("Longest repeating sequence length:", longest_repeating_sequence(s))
Viva Questions:
• What is a repeating sequence?
• How does max() function help?
Prepared By – Mr. Sachin Yadav
Program 18: Highest and Lowest Frequency Character
S/W & H/W Required: Python 3.x
Code [python]:
from collections import Counter
def freq_analysis(s):
count = Counter(s.replace(" ", ""))
max_char = max(count, key=count.get)
min_char = min(count, key=count.get)
return max_char, count[max_char], min_char, count[min_char]
s = input("Enter a string: ")
max_c, max_f, min_c, min_f = freq_analysis(s)
print("Highest Frequency:", max_c, "-", max_f)
print("Lowest Frequency:", min_c, "-", min_f)
Viva Questions:
• How to use Counter?
• How are dicts used for counting?
Prepared By – Mr. Sachin Yadav
Program 19: Stack implementation using array
S/W & H/W Required:
• Software: Python 3.x
• Hardware: Any standard PC or laptop
Code [python]:
stack = []
def push():
element = input("Enter element to push: ")
stack.append(element)
print(f"{element} pushed into stack.")
def pop():
if not stack:
print("Stack Underflow!")
else:
print(f"{stack.pop()} popped from stack.")
def display():
if not stack:
print("Stack is empty.")
else:
print("Stack:", stack[::-1])
while True:
print("\n1.Push\n2.Pop\n3.Display\n4.Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
push()
elif choice == 2:
Prepared By – Mr. Sachin Yadav
pop()
elif choice == 3:
display()
elif choice == 4:
break
else:
print("Invalid choice.")
Outcome: Stack is implemented using array with push, pop, and display functionalities.
Viva Questions:
• What is a stack?
• Explain LIFO with example.
• What is stack overflow and underflow?
Prepared By – Mr. Sachin Yadav
Program 20: Stack implementation using pointer (list)
S/W & H/W Required: Python 3.x, standard PC
Code [python]:
class Stack:
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop(self):
if not self.stack:
return "Stack Underflow"
return self.stack.pop()
def display(self):
print("Stack:", self.stack[::-1])
s = Stack()
s.push(10)
s.push(20)
s.display()
print("Popped:", s.pop())
Prepared By – Mr. Sachin Yadav
s.display()
Viva Questions:
• What is the difference between static and dynamic stack?
• What are advantages of dynamic memory allocation?
Prepared By – Mr. Sachin Yadav
Program 21: Multiple stack implementation
S/W & H/W Required: Python 3.x, PC
Code [python]:
size = 10
stack = [None]*size
top1 = -1
top2 = size
def push1(val):
global top1, top2
if top1 + 1 == top2:
print("Stack Overflow")
else:
top1 += 1
stack[top1] = val
def push2(val):
global top1, top2
if top2 - 1 == top1:
print("Stack Overflow")
else:
top2 -= 1
stack[top2] = val
Prepared By – Mr. Sachin Yadav
def pop1():
global top1
if top1 == -1:
print("Stack1 Underflow")
else:
print("Popped from Stack1:", stack[top1])
top1 -= 1
def pop2():
global top2
if top2 == size:
print("Stack2 Underflow")
else:
print("Popped from Stack2:", stack[top2])
top2 += 1
push1(5)
push2(100)
push1(10)
pop1()
pop2()
Outcome: Two stacks successfully managed in single array.
Prepared By – Mr. Sachin Yadav
Viva Questions:
• Why use multiple stacks?
• How is memory utilized better in two stacks?
Prepared By – Mr. Sachin Yadav
Program 22: Infix to Postfix Conversion
S/W & H/W Required: Python 3.x
Code [python]:
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
def infix_to_postfix(expression):
stack = []
result = ''
for ch in expression:
if ch.isalnum():
result += ch
elif ch == '(':
stack.append(ch)
elif ch == ')':
while stack and stack[-1] != '(':
result += stack.pop()
stack.pop()
else:
while stack and precedence(ch) <= precedence(stack[-1]):
result += stack.pop()
stack.append(ch)
while stack:
result += stack.pop()
return result
exp = "A*(B+C)"
print("Postfix:", infix_to_postfix(exp))
Prepared By – Mr. Sachin Yadav
Viva Questions:
• What is postfix expression?
• Why do we need infix to postfix conversion?
Prepared By – Mr. Sachin Yadav
Program 23: Queue using array
S/W & H/W Required: Python 3.x
Code [python]:
queue = []
def enqueue():
val = input("Enter element to enqueue: ")
queue.append(val)
print(f"{val} added to queue.")
def dequeue():
if not queue:
print("Queue Underflow")
else:
print(f"{queue.pop(0)} removed from queue.")
def display():
print("Queue:", queue)
enqueue()
enqueue()
display()
dequeue()
display()
Prepared By – Mr. Sachin Yadav
Viva Questions:
• What is queue?
• How is queue different from stack?
Prepared By – Mr. Sachin Yadav
Program 24: Dynamic queue implementation
S/W & H/W Required: Python 3.x
Code [python]:
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, val):
self.queue.append(val)
def dequeue(self):
if not self.queue:
return "Queue is empty"
return self.queue.pop(0)
def display(self):
print("Queue:", self.queue)
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.display()
print("Dequeued:", q.dequeue())
q.display()
Viva Questions:
• How is dynamic queue better than static?
Prepared By – Mr. Sachin Yadav
Program 25: Circular Queue
S/W & H/W Required:
Python 3.x, any IDE (VS Code, PyCharm), 2GB RAM, basic processor.
Code [python]:
class CircularQueue:
def __init__(self, size):
self.size = size
self.queue = [None]*size
self.front = self.rear = -1
def enqueue(self, data):
if (self.rear + 1) % self.size == self.front:
print("Queue is Full")
elif self.front == -1:
self.front = self.rear = 0
self.queue[self.rear] = data
else:
self.rear = (self.rear + 1) % self.size
self.queue[self.rear] = data
def dequeue(self):
if self.front == -1:
print("Queue is Empty")
elif self.front == self.rear:
temp = self.queue[self.front]
self.front = self.rear = -1
print("Dequeued:", temp)
else:
temp = self.queue[self.front]
self.front = (self.front + 1) % self.size
Prepared By – Mr. Sachin Yadav
print("Dequeued:", temp)
def display(self):
if self.front == -1:
print("Queue is Empty")
else:
i = self.front
while True:
print(self.queue[i], end=" ")
if i == self.rear:
break
i = (i + 1) % self.size
print()
cq = CircularQueue(5)
cq.enqueue(10)
cq.enqueue(20)
cq.enqueue(30)
cq.enqueue(40)
cq.enqueue(50)
cq.display()
cq.dequeue()
cq.enqueue(60)
cq.display()
Outcome:
Circular queue operations performed using list and modular arithmetic.
Viva Questions:
1. What is the difference between linear and circular queues?
2. What happens when rear crosses the size of the list?
3. What are real-life applications of circular queues?
Prepared By – Mr. Sachin Yadav
Program 26: Deque (Double Ended Queue) Implementation
Software & Hardware Required: Python 3.x, VS Code/Any IDE, 2GB RAM
Code [Python]:
from collections import deque
dq = deque()
# Inserting at rear
dq.append(10)
dq.append(20)
print("After adding at rear:", list(dq))
# Inserting at front
dq.appendleft(5)
print("After adding at front:", list(dq))
# Removing from rear
dq.pop()
print("After removing from rear:", list(dq))
# Removing from front
dq.popleft()
print("After removing from front:", list(dq))
Viva Questions:
• What is a deque?
• Which operations are allowed in deque?
• How is deque different from queue and stack?
Prepared By – Mr. Sachin Yadav
Program 27: Priority Queue
Software & Hardware Required:
Python 3.x, heapq module
Code [Python]:
import heapq
pq = []
heapq.heappush(pq, (2, "Task 2"))
heapq.heappush(pq, (1, "Task 1"))
heapq.heappush(pq, (3, "Task 3"))
print("Priority Queue:")
while pq:
print(heapq.heappop(pq))
Outcome:
Priority Queue executed using heapq.
Viva Questions:
• What is a priority queue?
• How is it different from normal queue?
• Which Python module supports priority queue?
Prepared By – Mr. Sachin Yadav
Program 28: Singly Linked List
Software & Hardware Required: Python 3.x
Code [Python]:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def display(self):
Prepared By – Mr. Sachin Yadav
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.append(30)
ll.display()
Outcome:
Singly linked list implemented with insert and display operations.
Viva Questions:
• What is a singly linked list?
• What is a node?
• How is it different from arrays?
Prepared By – Mr. Sachin Yadav
Program 29: Doubly Linked List
Software & Hardware Required: Python 3.x
Code [Python]:
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
new_node.prev = temp
Prepared By – Mr. Sachin Yadav
def display(self):
temp = self.head
while temp:
print(temp.data, end=" <-> ")
temp = temp.next
print("None")
dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.append(3)
dll.display()
Viva Questions:
• What is the use of a doubly linked list?
• How is it different from singly linked list?
Prepared By – Mr. Sachin Yadav
Program 30: Binary Search Tree (BST)
Software & Hardware Required: Python 3.x
Code [Python]:
class Node:
def __init__(self, key):
self.left = self.right = None
self.key = key
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
Prepared By – Mr. Sachin Yadav
root = None
for key in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, key)
print("In-order Traversal:")
inorder(root)
Outcome:
BST created and traversed using in-order traversal.
Viva Questions:
• What is a BST?
• Which traversal gives sorted output?
• Where is BST used?
Prepared By – Mr. Sachin Yadav
Program 31: Breadth First Search (BFS)
Software & Hardware Required: Python 3.x
Code [Python]:
from collections import deque
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
visited = set()
queue = deque(['A'])
print("BFS Traversal:")
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex, end=" ")
visited.add(vertex)
queue.extend(graph[vertex])
Prepared By – Mr. Sachin Yadav
Outcome:
Graph traversed using BFS.
Viva Questions:
• What data structure is used in BFS?
• How is BFS different from DFS?
• Where is BFS used in real life?
Prepared By – Mr. Sachin Yadav
Program 32: Depth First Search (DFS)
Software & Hardware Required: Python 3.x
Code [Python]:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
visited = set()
def dfs(vertex):
if vertex not in visited:
print(vertex, end=" ")
visited.add(vertex)
for neighbour in graph[vertex]:
dfs(neighbour)
print("DFS Traversal:")
dfs('A')
Outcome:
Graph traversed using DFS.
Prepared By – Mr. Sachin Yadav
Viva Questions:
• What is the use of DFS?
• What are the real-life applications of DFS?
• How is DFS implemented?
Prepared By – Mr. Sachin Yadav