K.R. Mangalam University: Data Structure Lab Manual
K.R. Mangalam University: Data Structure Lab Manual
Mangalam University
Submitted to : Submitted By :
Mr. Rahul Singh R C Vikram
Assistant Professor 2301840007
CSE SOET B.sc(Hons.) Data Science
Index
Serial Experiment Date Signature
No
Assignments 1
Code -
class ArrayOperations:
def __init__(self, capacity):
self.array = []
self.capacity = capacity
def display(self)
print("Current Array:", self.array)
R C Vikram
Data Structure Lab
array = ArrayOperations(capacity=5)
array.insert_at_end(10)
array.insert_at_end(20)
array.insert_at_position(1, 15)
array.insert_sorted(5)
array.insert_sorted(25)
array.display()
Output-
R C Vikram
Data Structure Lab
Assignment 2
Code-
class Stack:
def __init__(self, capacity):
self.stack = []
self.capacity = capacity
def is_empty(self):
return len(self.stack) == 0
def is_full(self):
return len(self.stack) == self.capacity
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack Underflow! Stack is empty.")
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
R C Vikram
Data Structure Lab
else:
return None
def display(self):
print("Current Stack:", self.stack)
stack = Stack(5)
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
print("Popped:", stack.pop())
stack.display()
Output-
Code-
def evaluate_postfix(expression):
stack = Stack(len(expression))
R C Vikram
Data Structure Lab
if char == '+':
stack.push(a + b)
elif char == '-':
stack.push(a - b)
elif char == '*':
stack.push(a * b)
elif char == '/':
stack.push(a // b)
return stack.pop()
postfix_expr = "53+62/*"
print("Postfix Evaluation:", evaluate_postfix(postfix_expr))
Output-
Postfix Evaluation: 0
Code-
def evaluate_prefix(expression):
stack = Stack(len(expression))
R C Vikram
Data Structure Lab
stack.push(a + b)
elif char == '-':
stack.push(a - b)
elif char == '*':
stack.push(a * b)
elif char == '/':
stack.push(a // b)
return stack.pop()
prefix_expr = "+*23/62"
print("Prefix Evaluation:", evaluate_prefix(prefix_expr))
Output-
Prefix Evaluation: 9
Code-
R C Vikram
Data Structure Lab
Output -
R C Vikram
Data Structure Lab
Assignment 3
class StandardQueue:
def __init__(self):
self.queue = []
def dequeue(self):
if not self.is_empty():
removed_item = self.queue.pop(0)
print(f"Dequeued: {removed_item}")
return removed_item
else:
print("Queue is empty!")
return None
def is_empty(self):
return len(self.queue) == 0
def display(self):
print("Queue contents:", self.queue)
R C Vikram
Data Structure Lab
sq.dequeue()
sq.display()
Output -
class CircularQueue:
def __init__(self, size):
self.queue = [None] * size
self.size = size
self.front = self.rear = -1
def dequeue(self):
if self.front == -1: # Queue is empty
print("Queue is empty!")
return None
removed_item = self.queue[self.front]
self.queue[self.front] = None
R C Vikram
Data Structure Lab
def display(self):
print("Queue contents:", self.queue)
Output -
Enqueued: 10
Enqueued: 20
Enqueued: 30
Dequeued: 10
Enqueued: 40
Queue contents: [40, 20, 30]
R C Vikram
Data Structure Lab
Code -
class RoundRobin:
def __init__(self, time_quantum):
self.time_quantum = time_quantum
self.processes = []
def execute(self):
print("\nRound Robin Execution:")
while self.processes:
process = self.processes.pop(0)
pid, burst_time = process["pid"], process["burst_time"]
if burst_time > self.time_quantum:
print(f"Executing process {pid} for {self.time_quantum} units.")
burst_time -= self.time_quantum
self.processes.append({"pid": pid, "burst_time": burst_time})
else:
print(f"Executing process {pid} for {burst_time} units. Process complete.")
self.display_queue()
def display_queue(self):
print("Remaining queue:", [p["pid"] for p in self.processes])
R C Vikram
Data Structure Lab
Output -
R C Vikram
Data Structure Lab
Assignment 4
Code -
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
if self.head.data == key:
R C Vikram
Data Structure Lab
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != key:
current = current.next
if current.next:
current.next = current.next.next
else:
print(f"Key {key} not found!")
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
Output -
R C Vikram
Data Structure Lab
Code -
class DNode:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
current = self.head
while current and current.data != key:
current = current.next
if current:
if current.prev:
current.prev.next = current.next
if current.next:
current.next.prev = current.prev
if current == self.head:
R C Vikram
Data Structure Lab
self.head = current.next
def display(self):
current = self.head
while current:
print(current.data, end=" <-> ")
current = current.next
print("None")
Output -
R C Vikram
Data Structure Lab
Code-
class CNode:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.tail = None
current = self.tail.next
prev = self.tail
if current.data == key:
if current == self.tail and current.next == self.tail: # Only one node
self.tail = None
elif current == self.tail:
prev.next = self.tail.next
R C Vikram
Data Structure Lab
self.tail = prev
else:
prev.next = current.next
def display(self):
if not self.tail:
print("List is empty!")
return
current = self.tail.next
while True:
print(current.data, end=" -> ")
current = current.next
if current == self.tail.next:
break
print("(Back to start)")
Output -
R C Vikram
Data Structure Lab
Code-
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
def __str__(self):
return f"Name: {self.name}, Phone: {self.phone}"
class ContactManagementSystem:
def __init__(self):
self.contacts = SinglyLinkedList()
R C Vikram
Data Structure Lab
def display_contacts(self):
print("Contact List:")
current = self.contacts.head
while current:
print(current.data)
current = current.next
Output -
R C Vikram
Data Structure Lab
Assignment 5
Q. Implementing and Analyzing Binary Search Tree Structure and its Operations-
implement and explore various operations on a Binary Search Tree (BST). Include
insertion, deletion, and searching for nodes within the BST. Create a program to
manage hierarchical data, such as an organizational chart, using the BST
Code -
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
R C Vikram
Data Structure Lab
if node is None:
return node
if key < node.key:
node.left = self._delete(node.left, key)
elif key > node.key:
node.right = self._delete(node.right, key)
else:
if node.left is None:
return node.right
elif node.right is None:
return node.left
temp = self._min_value_node(node.right)
node.key = temp.key
node.right = self._delete(node.right, temp.key)
return node
def inorder(self):
result = []
self._inorder(self.root, result)
return result
R C Vikram
Data Structure Lab
for el in elements:
bst.insert(el)
key = 40
found = bst.search(key)
print(f"Element {key} {'found' if found else 'not found'} in the BST.")
bst.delete(30)
print("Inorder Traversal after Deletion of 30:", bst.inorder())
Output -
R C Vikram
Data Structure Lab
Code -
class OrgNode:
def __init__(self, name, role):
self.name = name
self.role = role
self.left = None
self.right = None
def __str__(self):
return f"{self.name} ({self.role})"
class OrganizationTree:
def __init__(self):
self.root = None
def display_hierarchy(self):
self._display_hierarchy(self.root, 0)
R C Vikram
Data Structure Lab
print("\nOrganizational Chart:")
org_tree = OrganizationTree()
org_tree.add_employee("Alice", "CEO")
org_tree.add_employee("Bob", "CTO")
org_tree.add_employee("Charlie", "CFO")
org_tree.add_employee("David", "Engineer")
org_tree.add_employee("Eve", "Accountant")
org_tree.display_hierarchy()
Output -
Organizational Chart:
Eve (Accountant)
Charlie (CFO)
Alice (CEO)
David (Engineer)
Bob (CTO)
R C Vikram
Data Structure Lab
Assignment 6
Code -
class GraphMatrix:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)]
def display(self):
print("Adjacency Matrix:")
for row in self.graph:
print(row)
matrix_graph = GraphMatrix(5)
matrix_graph.add_edge(0, 1, 2)
matrix_graph.add_edge(0, 2, 4)
matrix_graph.add_edge(1, 3, 7)
matrix_graph.add_edge(2, 4, 1)
matrix_graph.display()
R C Vikram
Data Structure Lab
Output -
Adjacency Matrix:
[0, 2, 4, 0, 0]
[2, 0, 0, 7, 0]
[4, 0, 0, 0, 1]
[0, 7, 0, 0, 0]
[0, 0, 1, 0, 0]
Code -
class GraphList:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def display(self):
print("Adjacency List:")
for vertex, edges in self.graph.items():
print(f"{vertex}: {edges}")
list_graph = GraphList(5)
list_graph.add_edge(0, 1, 2)
list_graph.add_edge(0, 2, 4)
list_graph.add_edge(1, 3, 7)
list_graph.add_edge(2, 4, 1)
R C Vikram
Data Structure Lab
list_graph.display()
Output -
Adjacency List:
0: [(1, 2), (2, 4)]
1: [(0, 2), (3, 7)]
2: [(0, 4), (4, 1)]
3: [(1, 7)]
4: [(2, 1)]
Code -
bfs(list_graph.graph, 0)
Output -
BFS Traversal:
01234
R C Vikram
Data Structure Lab
Code -
print("DFS Traversal:")
dfs(list_graph.graph, 0)
print()
Output -
DFS Traversal:
01324
Code -
import heapq
R C Vikram
Data Structure Lab
while pq:
current_distance, current_node = heapq.heappop(pq)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node]:
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
dijkstra(list_graph.graph, 0)
Output -
R C Vikram
Data Structure Lab
Assignment 7
1. Linear Search
Non-Recursive Linear Search:
Code -
Output -
R C Vikram
Data Structure Lab
Code -
Output -
2. Binary Search
Non-Recursive Binary Search:
Code -
R C Vikram
Data Structure Lab
Output -
Code -
Output -
R C Vikram
Data Structure Lab
Efficiency Comparison:
● Linear Search:
○ Time Complexity: O(n)O(n)O(n)
○ Space Complexity: O(1)O(1)O(1) for non-recursive, O(n)O(n)O(n) for
recursive due to call stack.
● Binary Search:
○ Time Complexity: O(logn)O(\log n)O(logn)
○ Space Complexity: O(1)O(1)O(1) for non-recursive, O(logn)O(\log
n)O(logn) for recursive due to call stack
Code -
class TextDatabase:
def __init__(self):
self.data = []
R C Vikram
Data Structure Lab
db = TextDatabase()
db.add_record("Alice")
db.add_record("Bob")
db.add_record("Charlie")
db.add_record("David")
target = "Charlie"
result = db.search_record(target, method="binary")
print(f"Database Search: '{target}' found at index {result}" if result != -1 else f"'{target}'
not found")
Output -
R C Vikram
Data Structure Lab
Assignment 8
1. Bubble Sort
Code -
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
Output -
Bubble Sort Output: [11, 12, 22, 25, 34, 64, 90]
R C Vikram
Data Structure Lab
2. Quick Sort
Code -
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
Output -
Quick Sort Output: [11, 12, 22, 25, 34, 64, 90]
3. Merge Sort
Code -
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
R C Vikram
Data Structure Lab
Output -
Merge Sort Output: [11, 12, 22, 25, 34, 64, 90]
Comparison of Performance
R C Vikram