0% found this document useful (0 votes)
17 views15 pages

DSA Practical

Data structures programs

Uploaded by

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

DSA Practical

Data structures programs

Uploaded by

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

DSA LAB MANUAL PROGRAMS 1

1. PROGRAM TO IMPLEMENT STACK ADT: OUTPUT:

class Stack: Enter max size of the stack: 3


def __init__(self, max_size):
1. Push
self.stack = [] 2. Pop
self.max_size = max_size 3. Peek
4. Display
def push(self, data): 5. Exit
Enter choice: 1
if len(self.stack) == self.max_size: Enter data: 3
print("Stack Overflow")
else: 1. Push
self.stack.append(data) 2. Pop
3. Peek
4. Display
def pop(self): 5. Exit
if self.stack: Enter choice: 1
print(f"Popped: {self.stack.pop()}") Enter data: 4
else:
1. Push
print("Stack Underflow") 2. Pop
3. Peek
def peek(self): 4. Display
print(self.stack[-1] if self.stack else "Stack is empty") 5. Exit
Enter choice: 1
Enter data: 5
def display(self):
print(self.stack if self.stack else "Stack is empty") 1. Push
2. Pop
if __name__ == "__main__": 3. Peek
4. Display
stack = Stack(int(input("Enter max size of the stack: "))) 5. Exit
while True: Enter choice: 2
choice = int(input("\n 1. Push\n 2. Pop\n 3. Peek\n 4. Popped: 5
Display\n 5. Exit\nEnter choice: "))
if choice == 1: 1. Push
2. Pop
stack.push(int(input("Enter data: "))) 3. Peek
elif choice == 2: 4. Display
stack.pop() 5. Exit
elif choice == 3: Enter choice: 3
4
stack.peek()
elif choice == 4: 1. Push
stack.display() 2. Pop
elif choice == 5: 3. Peek
print("Exiting....") 4. Display
5. Exit
break Enter choice: 4
else: [3, 4]
print("Invalid choice")
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter choice: 5
Exiting....
2

2. PROGRAM TO IMPLEMENT QUEUE ADT: OUTPUT:

class Queue: Enter max size of the queue: 3


def __init__(self, max_size):
1. Enqueue
self.queue = [] 2. Dequeue
self.max_size = max_size 3. Front
4. Display
def enqueue(self, data): 5. Exit
Enter choice: 1
if len(self.queue) == self.max_size: Enter data: 5
print("Queue Overflow")
else: 1. Enqueue
self.queue.append(data) 2. Dequeue
3. Front
4. Display
def dequeue(self): 5. Exit
if self.queue: Enter choice: 1
print(f"Dequeued: {self.queue.pop(0)}") Enter data: 8
else:
1. Enqueue
print("Queue Underflow") 2. Dequeue
3. Front
def front(self): 4. Display
print(self.queue[0] if self.queue else "Queue is empty") 5. Exit
Enter choice: 2
Dequeued: 5
def display(self):
print(self.queue if self.queue else "Queue is empty") 1. Enqueue
2. Dequeue
if __name__ == "__main__": 3. Front
4. Display
queue = Queue(int(input("Enter max size of the queue: "))) 5. Exit
while True: Enter choice: 3
choice = int(input("\n1. Enqueue\n2. Dequeue\n3. Front\n4. 8
Display\n5. Exit\nEnter choice: "))
if choice == 1: 1. Enqueue
2. Dequeue
queue.enqueue(int(input("Enter data: "))) 3. Front
elif choice == 2: 4. Display
queue.dequeue() 5. Exit
elif choice == 3: Enter choice: 4
[8]
queue.front()
elif choice == 4: 1. Enqueue
queue.display() 2. Dequeue
elif choice == 5: 3. Front
print(“Exiting……”) 4. Display
5. Exit
break Enter choice: 5
else: Exiting……
print("Invalid choice")
3

3. PROGRAM TO IMPLEMENT SINGLY LINKED LIST: OUTPUT:

class Node: Nodes of singly linked list:


def __init__(self, data): 4
self.data = data 3
self.next = None 2
1 -> None
class SinglyLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
new_node.next = self.head
self.head = new_node

def display(self):
temp = self.head
print("Nodes of singly linked list:")
while temp:
print(temp.data, end="\n" if temp.next else " -> None\n")
temp = temp.next

sll = SinglyLinkedList()
sll.insert(1)
sll.insert(2)
sll.insert(3)
sll.insert(4)
sll.display()
4

4. PROGRAM TO IMPLEMENT DOUBLY LINKED OUTPUT:


LIST:
Nodes of doubly linked list:
class Node: 4 <-> 3 <-> 2 <-> 1 -> None
def __init__(self, data):
self.data = data
self.prev = None
self.next = None

class DoublyLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
new_node.next = self.head
if self.head:
self.head.prev = new_node
self.head = new_node

def display(self):
temp = self.head
print("Nodes of doubly linked list:")
while temp:
print(temp.data, end=" <-> " if temp.next else " ->
None\n")
temp = temp.next

dll = DoublyLinkedList()
dll.insert(1)
dll.insert(2)
dll.insert(3)
dll.insert(4)
dll.display()
5

5. PROGRAM TO IMPLEMENT CIRCULAR LINKED OUTPUT:


LIST:
Circular Linked List:
class Node: 1 -> 2 -> 3 -> 4 -> 1 (back to head)
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
new_node.next = new_node
else:
temp = self.head
while temp.next != self.head:
temp = temp.next
temp.next = new_node
new_node.next = self.head

def display(self):
if not self.head:
print("List is empty")
return
temp = self.head
print("Circular Linked List:\n ", end="")
while True:
print(temp.data, end=" -> ")
temp = temp.next
if temp == self.head:
print(f"{self.head.data} (back to head)")
break

cll = CircularLinkedList()
for i in [1, 2, 3, 4]:
cll.insert(i)
cll.display()
6

6. PROGRAM TO EVALUATE POSTFIX EXPRESSION: OUTPUT:

def evaluate_postfix(expression): Result of postfix expression '562+*31-


stack = [] /' is 20
for char in expression:
if char.isdigit():
stack.append(int(char))
else:
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
elif char == '*':
stack.append(a * b)
elif char == '/':
stack.append(a // b)
return stack.pop()

postfix_expression = "562+*31-/"
result = evaluate_postfix(postfix_expression)
print(f"Result of postfix expression '{postfix_expression}' is
{result}")
7

7. PROGRAM TO DESIGN AND IMPLEMENT THE OUTPUT:


BINARY TREE:
Constructed Tree:
class Node: -> 4
def __init__(self, val): -> 7
self.val = val -> 2
self.left = self.right = None -> 5
-> 3
class Tree: -> 1
def __init__(self):
self.root = None

def add(self, val):


if not self.root:
self.root = Node(val)
else:
self._add_node(self.root, val)

def _add_node(self, node, val):


if node.left is None:
node.left = Node(val)
elif node.right is None:
node.right = Node(val)
else:
self._add_node(node.left, val) if node.left else
self._add_node(node.right, val)

def show(self, node, lvl=0):


if node:
self.show(node.right, lvl + 1)
print(' ' * 4 * lvl + '->', node.val)
self.show(node.left, lvl + 1)

t = Tree()
for v in [7, 5, 4, 3, 2, 1]:
t.add(v)

print("Constructed Tree:")
t.show(t.root)
8

8. PROGRAM TO DESIGN AND IMPLEMENT BINARY OUTPUT:


SEARCH TREE:
Constructed BST:
class Node: -> 7
def __init__(self, val): -> 5
self.val = val -> 4
self.left = self.right = None -> 3
-> 2
class BST: -> 1
def __init__(self):
self.root = None

def add(self, val):


if not self.root:
self.root = Node(val)
else:
self._add_node(self.root, val)

def _add_node(self, node, val):


if val < node.val:
if node.left:
self._add_node(node.left, val)
else:
node.left = Node(val)
else:
if node.right:
self._add_node(node.right, val)
else:
node.right = Node(val)

def show(self, node, lvl=0):


if node:
self.show(node.right, lvl + 1)
print(' ' * 4 * lvl + '->', node.val)
self.show(node.left, lvl + 1)

bst = BST()
for v in [7, 5, 4, 3, 2, 1]:
bst.add(v)

print("Constructed BST:")
bst.show(bst.root)
9

9. PROGRAM TO DESIGN AND IMPLEMENT OUTPUT:


DIJKSTRA'S ALGORITHM:
A: Distance = 0, Path = A
import heapq B: Distance = 1, Path = A -> B
C: Distance = 3, Path = A -> B -> C
def dijkstra(graph, start): D: Distance = 4, Path = A -> B -> C -> D
dist = {node: float('inf') for node in graph}
dist[start] = 0
prev = {node: None for node in graph}
pq = [(0, start)]

while pq:
curr_dist, node = heapq.heappop(pq)
if curr_dist > dist[node]:
continue
for neighbor, weight in graph[node]:
new_dist = curr_dist + weight
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
prev[neighbor] = node
heapq.heappush(pq, (new_dist, neighbor))

def path(node):
p = []
while node:
p.insert(0, node)
node = prev[node]
return p

return {node: (dist[node], path(node)) for node in graph}

graph = {
'A': [('B', 1), ('C', 4)],
'B': [('C', 2), ('D', 5)],
'C': [('D', 1)],
'D': []
}

result = dijkstra(graph, 'A')

for node, (distance, p) in result.items():


print(f"{node}: Distance = {distance}, Path = {' -> '.join(p)}")
10

10. PROGRAM TO SOLVE MERGE SORT.: OUTPUT:

print('Merge Sort: ') Merge Sort:


A = [] Enter Number of Elements in the List: 3
n = int(input('Enter Number of Elements in the List: ')) Enter the Element 1 :5
for i in range(0, n): Enter the Element 2 :2
x = int(input('Enter the Element %d :' %(i+1))) Enter the Element 3 :6
A.append(x) Original List:
print('Original List: ') [5, 2, 6]
print(A) Splitting [5, 2, 6]
Splitting [5]
def Merge(left, right, A): Splitting [2, 6]
i=j=k=0 Splitting [2]
while(i < len(left) and j < len(right)): Splitting [6]
if(left[i] < right[j]): Merging [2, 6]
A[k] = left[i] Merging [2, 5, 6]
i=i+1 Sorted List:
else:
A[k] = right[j] [2, 5, 6]
j += 1
k += 1

while(i < len(left)):


A[k] = left[i]
i += 1
k += 1

while(j < len(right)):


A[k] = right[j]
j += 1
k += 1
print('Merging', A)

def MergeSort(A):
print('Splitting', A)
n = len(A)
if(n > 1):
mid = n // 2
left = A[:mid]
right = A[mid:]
MergeSort(left)
MergeSort(right)
Merge(left, right, A)

MergeSort(A)
print("Sorted List:\n")
print(A)
11

11. PROGRAM TO SOLVE INSERTION SORT: OUTPUT:

Sorted array is :
def insertionSort(arr): [5, 6, 11, 12, 13]
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]


insertionSort(arr)

lst = []
print("Sorted array is : ")
for i in range(len(arr)):
lst.append(arr[i])
print(lst)

12.A)PROGRAM TO IMPLEMENT LINEAR OUTPUT:


SEARCH:
n = int(input("Enter the number of elements:")) Enter the number of elements:4
a = [] Enter the elements:1
Enter the elements:3
for i in range(n): Enter the elements:4
x = int(input("Enter the elements:")) Enter the elements:6
a.append(x) Enter the element to search:4
Element found
def linear(e):
for i in range(n):
if a[i] == e:
print("Element found")
break
else:
print("Element not found")

e = int(input("Enter the element to search:"))


linear(e)
12

12.B)PROGRAM TO IMPLEMENT OUTPUT:


BINARY SEARCH:
Enter the target number: 11
def binary_search(a, target): Element found at index 5
left = 0
right = len(a) - 1
found = False

while left <= right:


mid = (right + left) // 2
if a[mid] == target:
found = True
break
elif a[mid] < target:
left = mid + 1
else:
right = mid - 1

if found:
print("Element found at index ", mid)
else:
print("Element not found")

a = [1, 3, 5, 7, 9, 11, 13, 15]


target = int(input("Enter the target number: "))
binary_search(a, target)

ALGORITHMS
1. STACK ADT
 Initialize an empty stack.
 Push element: Add the element to the stack.
 Pop element: Remove and return the top element of the stack.
 Peek: Return the top element without removing it.

 Check if the stack is empty.


 Display all elements in the stack.
13

2. QUEUE ADT
 Initialize an empty queue.
 Enqueue element: Add the element to the rear of the queue.

 Dequeue element: Remove and return the front element of the queue.
 Peek: Return the front element without removing it.
 Check if the queue is empty.
 Display all elements in the queue.

3. SINGLY LINKED LIST


 Initialize an empty linked list.
 Insert element: Add a node at the end or beginning.
 Delete element: Remove a node by value.
 Search element: Traverse and find a node by value.
 Display elements: Traverse and print all node values.

 Check if the list is empty.

4. DOUBLY LINKED LIST


 Initialize an empty doubly linked list.
 Insert element: Add a node at the beginning, middle, or end.
 Delete element: Remove a node by value.

 Search element: Traverse and find a node.


 Traverse: Move forward or backward through nodes.
 Display all elements from both directions.

5. CIRCULAR LINKED LIST


 Initialize an empty circular linked list.

 Insert element: Add a node and make it point to the head.


 Delete element: Remove a node by value.
 Search element: Traverse circularly to find a node.
 Display elements: Traverse circularly and print all nodes.
 Check if the list has only one node.
14

6. EVALUATE POSTFIX EXPRESSION


 Initialize an empty stack.
 For each token in the expression:

o If it's an operand, push it to the stack.


o If it's an operator, pop two operands from the stack, apply the operator, and
push the result.
 After processing, the stack contains the final result.
 Return the result.

7. BINARY TREE
 Initialize an empty tree with a root node.

 Insert element: Add a node based on binary tree rules (left or right).
 Search element: Recursively search for a node by value.
 Traverse tree: Perform in-order, pre-order, or post-order traversal.
 Delete element: Remove a node while maintaining binary tree properties.
 Display all nodes in a specific order.

8. BINARY SEARCH TREE


 Initialize an empty binary search tree (BST).
 Insert element: Add nodes recursively by comparing values.
 Search element: Find a node by recursively comparing values.
 Delete element: Remove a node and ensure the BST properties.

 Traverse tree: Perform in-order traversal to get sorted elements.


 Display elements in sorted order.

9. DIJKSTRA'S ALGORITHM
 Initialize a set of visited nodes and a distance map.
 Set the initial node distance to 0, and others to infinity.

 For the current node, check its neighbors and update their distances.
 Mark the current node as visited and move to the next closest unvisited node.
 Repeat until all nodes are visited.
 Return the shortest distance to each node.
15

10. MERGE SORT


 Divide the list into two halves recursively.

 Recursively sort each half.


 Merge the two sorted halves into a single sorted list.
 Repeat the process until all sublists are merged.
 Return the sorted list.

11. INSERTION SORT


 Traverse the list from the second element.
 For each element, insert it into the correct position in the sorted portion of the list.
 Shift elements to the right to make room for the current element.
 Continue until all elements are sorted.
 Return the sorted list.

12. SEARCH ALGORITHMS


 LINEAR SEARCH:
o Traverse through each element in the list.
o Compare each element with the target.
o If found, return the index; otherwise, return -1.
 BINARY SEARCH:
o Start with the middle element.
o If the target is smaller, search the left half; if larger, search the right half.
o Repeat until the element is found or the sublist is empty.
o Return the index or -1 if not found.

You might also like