SYCS Data Structure Practical Manual
SYCS Data Structure Practical Manual
return stack.pop()
Output-
Explanation About important methods used in above program:
Sr.no Method name Explanation
Point to Remember:
------🡪
● Note: you can’t remove any element from empty stack you will receive stack
underflow Exception.
● You can’t add any element if stack is already full if you do so , you will receive stack
overflow Exception.
-------------------------------------------------------------------------------------------------------------
Program 1A1) STACK ADT USING LIST
# Python program to demonstrate stack implementation using list
stack = []
print('Initial stack')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
OUTPUT:
You can implement stack with deque , queue and singly linked List .
Program 1A.2)
# Python program to demonstrate stack implementation using collections.deque
print('Initial stack:')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
OUTPUT:
-------------------------------------------------------------------------------------------------------------
PROGRAM 1.A.3 STACK Implementation using queue
#Python program to demonstrate stack implementation using queue module
# Initializing a stack
stack = LifoQueue(maxsize=3)
PROGRAM 1A4)
Implementation STACK ADT using a singly linked list
# Python program to demonstrate stack implementation using a linked list.
# node class
class Node:
def init (self, value):
self.value = value
self.next = None
class Stack:
# Initializing a stack.
# Use a dummy node, which is #
easier for handling edge cases.
def init (self):
self.head = Node("head")
self.size = 0
# String representation of the stack
def str (self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
cur = cur.next
return out[:-3]
# Get the current size of the stack
def getSize(self):
return self.size
# Driver Code
if name == " main ":
stack = Stack()
for i in range(1, 11):
stack.push(i)
print(f"Stack: {stack}")
OUTPUT:
Methods :
The linked list has two methods addHead(item) and removeHead() that run in constant time.
These two methods are suitable to implement a stack.
● getSize()– Get the number of items in the stack.
● isEmpty() – Return True if the stack is empty, False otherwise.
● peek() – Return the top item in the stack. If the stack is empty, raise an exception.
● push(value) – Push a value into the head of the stack.
● pop() – Remove and return a value in the head of the stack. If the stack is empty, raise an
exception.
Program 1B QUEUE ADT
# Python program to demonstrate queue implementation using list
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
OUTPUT:
METHODS USED:
● Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow
condition – Time Complexity : O(1)
● Dequeue: Removes an item from the queue. The items are popped in the same order in which
they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time
Complexity : O(1)
● Front: Get the front item from queue – Time Complexity : O(1)
● Rear: Get the last item from queue – Time Complexity : O(1)
-------------------------------------------------------------------------------------------------------------
PROGRAM 1C: implementation of LIST ADT.
# Declaring a list with integer and string elements
list = [10, 20, 30, "New Delhi", "Mumbai"]
# printing list
print("List elements are: ", list)
# adding elements
list.append (40)
list.append (50)
list.append ("Chennai")
# removing elements
list.pop () ;
# printing list
print ("List elements: ", list)
# removing elements
list.pop () ;
# printing list
print ("List elements: ", list)
OUTPUT:
Methods used:
Python List append() Method
It is used to add/append an object (which will be passed in method as parameter) to the list.
Syntax:
list.append(element)
Here,
● list - is the name of the list.
● append() - is the method name, that is used to add element/object to the list.
● element - is an element (which is considered as on object or element) to be added in the list.
Python List pop() Method
It is used to remove/pop an object from the list.
Syntax:
list.pop()
Here,
● list is the name of the list.
● pop() is the method name that is used to remove last element from the list.
Practical 2-Write a program to implement Singly Linked list with insertion, deletion, traversal
operations .
Practical 2(A)-Write a program to implement singly linked list with insertion
# A complete working Python program to demonstrate all insertion methods of linked list
# Node class
class Node:
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
Output-
Practical 2(B)- write a program to implement singly linked list with deletion
# A complete working Python3 program to
# demonstrate deletion in singly
# linked list with class
# Node class
class Node:
class LinkedList:
temp = None
# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
Output-
# Node class
class Node:
class LinkedList:
# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()
Output-
Methods used:
● insert(): Add an item to the linked list at the head of the list
● find(): Find an item within the linked list
● remove(): Remove a given item with a given value
● is_empty(): Returns whether the linked list is empty or not
● get_count(): Returns the number of items in the linked list
● deleteAt(index): delete an item at a given index
● findAt(index): find the item at the given index
● insertAt(index): insert an item at a given index
Practical 3-Write a program to implement Doubly Linked list with insertion, deletion, traversal
operations
Practical 3(A)- Write a program to implement doubly linked list with insertion.
# Create the Node class
class Node:
def init (self, data):
self.data = data
self.next = None
self.prev = None
dllist = doubly_linked_list()
dllist.push(12)
dllist.push(8)
dllist.push(62)
dllist.insert(dllist.head.next, 13)
dllist.listprint(dllist.head)
Output-
Practical 3(B)-Write a program to implement doubly linked list with deletion
# Program to delete a node in a doubly-linked list For Garbage collection
import gc
class DoublyLinkedList:
# Base Case
if self.head is None or dele is None:
return
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head
# and previous as None (already None)
new_node.next = self.head
# Driver code
# Start with empty list
dll = DoublyLinkedList()
Output-
class DoublyLinkedList:
def init (self):
self.start_node = None
def traverse_list(self):
if self.start_node is None:
print("List has no element")
return
else:
n = self.start_node
while n is not None:
print(n.item , " ")
n = n.nref
OUTPUT:
Practical 4-Write a program to implement Stack with insertion, deletion, traversal operations
# Python program to
# demonstrate stack implementation
# using collections.deque
stack = deque()
print('Initial stack:')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
Output-
Practical 5-Write a program to implement Queue with insertion, deletion, traversal
operations.
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
# Uncommenting print(queue.pop(0))
# will raise and IndexError
# as the queue is now empty
Output-
Practical 6-Write a program to implement Priority Queue with insertion, deletion, traversal
operations
self.data = value
self.priority = pr
self.next = None
self.front = None
else:
# Assigning it to self.front
self.front = newNode
while temp.next:
temp = temp.next
newNode = PriorityQueueNode(value,priority)
newNode.next = temp.next
temp.next = newNode
else:
# Driver code
if name == " main ":
Output-
Practical 7- Write a program to implement Binary Tree with insertion, deletion, traversal
operations
Practical 7(A)- BST with insertion
class Tree:
Output-
else:
if (node.left is None and node.right is None):
if(temp.left == node):
temp.left = None
else:
temp.right = None
node = None
else:
temp = node.right
while(temp.left is not None):
temp = temp.left
node.value = temp.value
node.right.Delete(temp,temp.value)
Root = Tree(6)
Root.Insert(4)
Root.Insert(2)
Root.Insert(5)
Root.Insert(9)
Root.Insert(8)
Root.Insert( 10)
Root.Delete(Root, 6)
print ('\n 6 is deleted: ',end ='')
Root.Inorder(Root)
Output-
class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key
if root:
if root:
if root:
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Preorder traversal of binary tree is")
printPreorder(root)
class NodeTree(object):
def init__(self, left=None, right=None):
self.left = left
self.right = right
def children(self):
return self.left, self.right
def make_tree(nodes):
'''
Function to make tree
:param nodes: Nodes
:return: Root of the tree
'''
while len(nodes) > 1:
(key1, c1) = nodes[-1]
(key2, c2) = nodes[-2]
nodes = nodes[:-2]
node = NodeTree(key1, key2)
nodes.append((node, c1 +
c2))
nodes = sorted(nodes, key=lambda x: x[1], reverse=True)
return nodes[0][0]
-------------------------------------------------------------------------------------------------------------
Practical 9-Write a program to implement Graph with insertion, deletion, traversal
import collections
# BFS algorithm
def bfs(graph, root):
while queue:
Output-
-------------------------------------------------------------------------------------------------------------
Practical 10-
Write a program to implement Travelling Salesman Problem.
------------------------------------------------------------------------------------------------------------
Travelling Salesman Problem
Travelling Sales Person Problem
The traveling salesman problems abide by a salesman and a set of cities. The salesman has to visit
every one of the cities starting from a certain one (e.g., the hometown) and to return to the same city.
The challenge of the problem is that the traveling salesman needs to minimize the total length of the
trip.
Suppose the cities are x1 x2 xn where cost cij denotes the cost of travelling from city xi to xj. The
travelling salesperson problem is to find a route starting and ending at x1 that will take in all cities with
the minimum cost.
Example: A newspaper agent daily drops the newspaper to the area assigned in such a manner that
he has to cover all the houses in the respective area with minimum travel cost. Compute the minimum
travel cost.
# Python3 program to implement traveling salesman
# problem using naive approach.
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if name == " main ":
Output-
-------------------------------------------------------------------------------------------------------------
Practical 11-Write a program to create basic Hash Table for insertion, deletion, traversal
operations(assume that there are no collisions)
# Python program to demonstrate working of HashTable
hashTable = [[],] * 10
# Python program to demonstrate working of HashTable
hashTable = [[],] * 10
def checkPrime(n):
if n == 1 or n == 0:
return 0
return 1
def getPrime(n):
if n % 2 == 0:
n=n+1
return n
def hashFunction(key):
capacity = getPrime(10)
return key % capacity
def removeData(key):
index = hashFunction(key)
hashTable[index] = 0
insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
print(hashTable)
Output-
Practical 12-Write a program to create hash table to handle collisions using overflow
chaining.
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
# Creating Hashtable as
# a nested list.
HashTable = [[] for _ in range(10)]
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)
# Driver Code
insert(HashTable, 10, 'Allahabad')
insert(HashTable, 25, 'Mumbai')
insert(HashTable, 20, 'Mathura')
insert(HashTable, 9, 'Delhi')
insert(HashTable, 21, 'Punjab')
insert(HashTable, 21, 'Noida')
display_hash (HashTable)
Output-