You are on page 1of 39

Lab Manual: Data Structures Laboratory

Assignment No. 1
Title of Assignment: Write a menu driven program to perform following operations on
Singly linked list: Create Insert, Delete and Display.
Design Analysis / Implementation Logic:

Algorithms and Requirements:

Create and Insert:


1. Ask the user to enter the data to be entered in the SLL one element at a time. For the
1st data create a node and initialize the 1 pointers to NULL.
2. From the second element entry onwards, traverse the SLL till the end with the help of
the forward pointer and create a new node, assign the data to it, its next pointer should
point to NULL.

Delete :
1. Accept the data which is to be deleted from the SLL.
2. Traverse the entire SLL from the 1st node and compare the data of every node with
the data entered by the user.
3. If match occurs delete the node. Deletion is accomplished by assigning the next
pointer of the previous node to the next node. Free the memory of the current node.

Display :

1. Begin with the 1st node in the SLL, print the data of all the nodes of the SLL in the
serial order with the help of the next pointer.

Testing:
Test Conditions:

Simple input of random numbers. After every insertion display to see if all the
contents are displayed properly. After every deletion also do the same. Delete nodes
at different locations in the SLL for eg, start node, last node and middle node. Make
sure that your delete function works for all cases.

Input:
Enter data ( could be words, characters or numbers) to be stored in the singly linked
list. Every node in
the SLL would contain 2fields: data, pointer.

Output :
Display the list of elements in the serial order as they appear in the SLL.

1
Lab Manual: Data Structures Laboratory

FAQS:

1. How to insert the new node in Singly Link List?

2. How to delete the node from front of Singly Link List ?

3. How to delete the node from end of Singly Link List ?

4. How to delete the node in between of Singly Link List ?

Conclusion:
In this assignment we have studied the basics about dynamic memory allocation and
how to create singly linked list and various operations on it.

2
Lab Manual: Data Structures Laboratory

Assignment No. 2
Title of Assignment: Write a menu driven program to perform following operations on
doubly linked list : Create, Insert, Delete, Display, Sort and Merge.

Algorithms:

Create and Insert:


1. Ask the user to enter the data to be entered in the DLL one element at a time. For
the 1st data create a node and initialize the 2 pointers to NULL.
2. From the second element entry onwards, traverse the DLL till the end with the
help of the forward pointer and create a new node, assign the data to it, its left
pointer should point to the node which was the last node previously and its right
pointer should point to NULL.

Delete :
1. Accept the data which is to be deleted from the DLL.
2. Traverse the entire DLL from the 1st node and compare the data of every node
with the data entered by the user.
3. If match occurs delete the node. Deletion is accomplished by assigning the
forward pointer of the previous node to the next node and the backward pointer
of the next node to the previous node. Free the memory of the current node.

Display :

1. Begin with the 1st node in the DLL, print the data of all the nodes of the DLL in
the serial order with the help of the next pointer.

Testing:
Test Conditions:

Simple input of random numbers. After every insertion display to see if all the
contents are displayed properly. After every deletion also do the same. Delete nodes
at different locations in the DLL for e.g., start node, last node and middle node. Make
sure that your delete function works for all cases.

Input:
Enter data (could be words, characters or numbers) to be stored in the doubly linked list.
Every node in the DLL would contain 3 fields: data, left pointer and right pointer.

Output:
Display the list of elements in the serial order as they appear in the DLL.

3
Lab Manual: Data Structures Laboratory

FAQS:

1. How to insert the new node in Doubly Link List?

2. How to delete the node from front of Doubly Link List ?

3. How to delete the node from end of Doubly Link List ?

4. How to delete the node in between of Doubly Link List ?

Conclusion:
In this assignment we have studied about doubly linked list, its advantages over
singly linked list and various operations on it.

Assignment No. 3

4
Lab Manual: Data Structures Laboratory

Title of Assignment: Write a program to represent the polynomial as a circular linked


list and write a menu driven program to perform addition,
multiplication and evaluation.

Algorithms:

Addition of 2 polynomials.

1. Begin with 2 pointers initialized to the head of the 2 CLLs. Move the pointers one
location.
2. Check the exponent values in both the nodes. If they are same, add the coefficients,
create the node for the resultant CLL and insert the addition of the coefficients and
the exponent. If they are not the same copy the coefficient and exponent, of the larger
exponent value to the resultant polynomial. In the first case move both pointers
forward and in the latter move the pointer of the polynomial whose node has been
copied. At every step a node has to be created for the third polynomial.
3. The above step to be performed repeatedly till one of the pointers reaches the head
node back again. In that case copy the contents of the other list to the end of the
resultant list.
4. Finally connect the last node of the resultant to the first, making it a circular list.

Multiplication of 2 polynomials :

1. Begin with 2 pointers initialized to the head of the 2 CLLs. Move the pointers one
location.
2. Keeping the pointer in 1st list at the same node, move the pointer of the 2nd list over
the entire list. Multiply the coefficients and add the exponents at every stage. Insert
the coeff, exp pair in a new node in the 3rd list.
3. After the entire 2nd list has been traversed once, move the pointer of the 1st list to the
next node and position pointer of the 2nd list back to the 1st node and continue the
above process.
4. Before inserting the new coeff, exp pair in the third list, traverse the entire list and if
any node with same exponent is already present the new coefficient must be added to
the previous one. Also the exponent should be entered in the list in the sorted fashion
(descending order of exponents).
5. When the pointer of the 1st list reaches the head node, multiplication is complete.
Connect the pointer of the last node of the 3rd list back to the front, making it circular
and terminate.

5
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:
Addition of two polynomials :

Enter input :
12x^6 +34.5x^5 +x +1 =0
14x^5 +22x =0
Addition of the 2 polynomials is :
12x^6 +48.5 x^5 +23x+1=0
Multiplication of the 2 polynomials is :

Enter input :
x^2 +x +1 =0
2x+2=0
Multiplication of the above 2 polynomials is
2x^3 +4x^2 +4x+2=0.
Take x as input from user and evaluate any of the above polynomials and display result.

Input:
Polynomials entered in the circular linked list. Every node in the C.L.L will have an float
coefficient, integer exponent and a pointer to the next node. Special symbols (such as 0.0
and 0) should be stored in the first node since this is a circular list. The entry should be
done in a descending order of exponents.

Output:
Resultant polynomial after addition and multiplication. Take the value of x from user and
evaluate the resultant polynomial.

FAQS:

1. How to insert the new node in Circular Link List?

2. How to delete the node from Circular Link List ?

3. What is use of the Circular Link List?

4. How to perform multiplication of two polynomials?

5. How to perform Addition of the two polynomials?

Conclusion:
In this assignment we have studied circular linked list and also how to implement
polynomials using it.

6
Lab Manual: Data Structures Laboratory

Assignment No. 4
Title of Assignment: Represent circular Queue and Double ended queue using Linked
representation and write a program to perform the following
operations : Insert, Delete.

Algorithms:

Create and Insert:

1. Maintain two counters front and rear which will always point to the front of the queue
and rear of the queue respectively. Initially both front and rear could point to the 1st
location of the array
2. When the Insert queue function or the add function is called, the rear should be
incremented by 1 position. Since we want to maintain a circular queue, advance rear
clockwise in the array (rear:=(rear+1)mod n), where n is the length of the array.
3. Check if front and rear are the same location. If so, it means queue is full, else add the
element in the position pointed to by rear.

Delete :

1. Check if front and rear are the same location. If so, it means queue is empty, else
increment the front by one position clockwise the same way we did to rear previously.
Then assign the item in that location to a variable and return.

(Note that queue full and queue empty are apparently having the same checking criteria,
but one is done after incrementing and the other is done before.)

Finding front :

1. Would proceed similar to delete except that after the variable has been returned, we
need to take front counter back 1 position to where it was before.

Finding rear :
1. Check if front and rear point to same location, if so say queue empty.
2. If not, return the element pointed to by the rear counter as the rear element of the
queue.

7
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:

Simple input of random numbers. After every insertion use function find rear to see if the
element is added properly. After every deletion also do the same. Also perform find front
prior to delete and make sure the same element is displayed in both cases.

Input:
Enter data ( could be words, characters or numbers) to be stored in the circular queue.
Every node in the circular queue would the data field. The queue should be implemented
as an array of data.

Output:
Display the item deleted from the queue at any time when the delete function is called

FAQS:

1. How to insert the new node in Circular queue & double ended queue?

2. How to delete the node from the front end of the Circular queue & double ended
queue ?

3. What is difference between Circular queue & double ended queue?

4. How to search the element in circular queue & double ended queue?

Conclusion:
In this assignment we have studied queue and doubly ended queue and how to
implement them using singly circular and doubly circular linked lists.

8
Lab Manual: Data Structures Laboratory

Assignment No.5
Title of Assignment: Creation of binary tree and perform recursive and non-recursive
traversals.

Algorithms:

Create and Insert:


1. Accept a random order of numbers from the user. The first number would be inserted
at the root node.
2. Thereafter, for every number ask user at which location he want to insert node. If he
said left than proceed left of the BT, else proceed right.
3. Perform this till you reach a null pointer, the place where the present data is to be
inserted.
4. Allocate a new node and assign the data in this node and allocate pointers
appropriately.

Traversals (Recursive):

1. Inorder: The recursive function will receive the root of the tree (or subtree) from
where inorder traversal is to be initiated. Algorithm is to proceed left, which in this
case is to call the same function with the left child of the node, print the data and then
proceed right, which in this case is to call the same function with the right child of the
node.
2. Preorder : Inorder was LDR, first move left, access data and then move right.
Preorder is DLR, first access data, move left and then move right.
3. Post order is LRD, first move left, then move right and then access the data.

Traversals (Non Recursive)

1. The same effect which happened during the recursive run needs to be effected here.
2. Declare a stack which holds pointers ( the nodes of the BT).
3. In the inorder case, begin with a loop which moves left as far as it can, pushing the
current node on the stack.
4. When you reach null, pop a node from the stack, access and display its data, move
right and go back to step 3. If stack is empty at step 4, exit the loop.
5. The preorder and postorder traversals would proceed in an identical manner, except
the position of displaying the contents of data would vary.

9
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:

Simple input of random numbers. Display the inorder traversal. It must be a sorted
list of the numbers entered, since a BT has been created. This would be prove that the
BT has been constructed properly. The preorder and post order traversals would give
a listing of data, which could be checked by drawing the BT on paper and checking if
it were true.

Input:
Enter data ( numbers) to be stored in the binary search tree. Every node in the BT would
contain 3 fields: data, left child pointer and right child pointer.

Output:
Display the list of elements in the serial order as they appear in the three traversals:
inorder, preorder and postorder. (both recursively and non recursively)

FAQS:

1. What is the time complexity of binary tree algorithm?

2. What are right and left spin binary trees?

3. What is the concept of threads in trees? How it is helpful?

4. What is height and weight balanced trees?

Conclusion:
In this assignment we have studied about trees and its applications. We have also
studied how to implement the trees and traversals on trees.

10
Lab Manual: Data Structures Laboratory

Assignment No. 6
Title of Assignment: Creation of binary Search tree and perform recursive and non-
recursive traversals.

Algorithms:

Create and Insert:


1. Accept a random order of numbers from the user. The first number would be
inserted at the root node.
2. Thereafter, every number is compared with the root node. If less than
or equal to the data in the root node, proceed left of the BST, else proceed right.
3. Perform this till you reach a null pointer, the place where the present
data is to be inserted.
4. Allocate a new node and assign the data in this node and allocate
pointers appropriately.

Traversals (Recursive):

1. Inorder: The recursive function will receive the root of the tree (or subtree) from
where inorder traversal is to be initiated. Algorithm is to proceed left, which in this
case is to call the same function with the left child of the node, print the data and then
proceed right, which in this case is to call the same function with the right child of the
node.
2. Preorder : Inorder was LDR, first move left, access data and then move right.
Preorder is DLR, first access data, move left and then move right.
3. Post order is LRD, first move left, then move right and then access the data.

Traversals (Non Recursive)

1. The same effect which happened during the recursive run needs to be effected here.
2. Declare a stack which holds pointers ( the nodes of the BST).
3. In the inorder case, begin with a loop which moves left as far as it can, pushing the
current node on the stack.
4. When you reach null, pop a node from the stack, access and display its data, move
right and go back to step 3. If stack is empty at step 4, exit the loop.
5. The preorder and postorder traversals would proceed in an identical manner, except
the position of displaying the contents of data would vary.

11
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:

Simple input of random numbers. Display the inorder traversal. It must be a sorted
list of the numbers entered, since a BST has been created. This would be prove that
the BST has been constructed properly. The preorder and post order traversals would
give a listing of data, which could be checked by drawing the BST on paper and
checking if it were true.

Input:
Enter data (numbers) to be stored in the binary search tree. Every node in the BST would
contain 3 fields: data, left child pointer and right child pointer.

Output:
Display the list of elements in the serial order as they appear in the three traversals:
inorder, preorder and postorder. (both recursively and non recursively)

FAQS:
1. What is the time complexity of binary search algorithm?

2. What are right and left spin binary trees?

3. What is the concept of threads in trees? How it is helpful?

4. What is height and weight balanced trees?

Conclusion:
In this assignment we have studied about binary search trees, its applications and
implementation.

12
Lab Manual: Data Structures Laboratory

Assignment No. 7
Title of Assignment: Write a program to create a Binary tree and find the height of tree
and print it’s leaf nodes. Find it’s mirror image, print original and
mirror image using level-wise printing.

Algorithms:

Create and Insert:


1. Accept a random order of numbers from the user. The first number would be inserted
at the root node.
2. Thereafter, every number is compared with the root node. If less than or equal to the
data in the root node, proceed left of the BST, else proceed right.
3. Perform this till you reach a null pointer, the place where the present data is to be
inserted.
4. Allocate a new node and assign the data in this node and allocate pointers
appropriately.

Height of BST :

1. This algorithm is based on the idea of storing the nodes of every level of the BST in a
dynamic queue (link list). It is also simultaneously useful to print the tree level wise.
The total number of levels accessed would be the height of the tree.
2. Initialize the contents of the list with the root of the BST. The counter
no_of_nodes_in_current_level =1 and the level_accessed =1.
3. Access no_of_nodes_in_current_level from the link list and add all their children to
the list at the end and simultaneously keep track of the number of nodes accessed in
the next level in a variable which at the end is assigned back to
no_of_nodes_in_current_level. Also increment level_accessed, indicating one more
level accessed in the BST.
4. Continue step 3 repeatedly till no_of_nodes_in_current_level is 0, which means no
more nodes in the next level. The value stored in the variable level_accessed is the
height of the BST.

(The above is a non recursive implementation to find the height of the BST. One could
also write a recursive algorithm to do the same.)

13
Lab Manual: Data Structures Laboratory

Leaf Nodes of BST :

1. There are many algorithms to find the leaf nodes of a BST. The one considered here
is based on the idea that one could do a simple inorder traversal of the BST and just
before printing the data as one normally does in an inorder traversal, check if both the
left and right nodes are NULL. If so, it means the node under consideration is a leaf
node and must be printed.
2. Inorder: The recursive function will receive the root of the tree (or subtree) from
where inorder traversal is to be initiated. Algorithm is to proceed left, which in this
case is to call the same function with the left child of the node, print the data if both
left and right pointers are NULL and then proceed right, which in this case is to call
the same function with the right child of the node.
3. Thus all the leaf nodes of the BST are printed.

Mirror of Tree :

1. Following is a algorithm of a recursive function to find mirror of the tree. The


function mirror_Tree accepts a pointer to a tree as the parameter. Initially the root
node is passed later the roots of the subsequent subtrees are passed as the parameter.
2. The function begins by checking if the pointer passed is not NULL. If not, allocates a
new node. Assigns the data of the original node to the copied node. Assigns the left
child of the new node by calling the function mirror Tree with the right child of the
original node and assigns the right child of the new node by calling the function
mirror_Tree with the left child of the original node. If the pointer passed is NULL,
NULL is returned by the function else the new node created is returned.

Level wise printing :

1. This algorithm is based on the idea of storing the nodes of every level of the BST in a
dynamic queue (link list).
2. Initialize the contents of the list with the root of the BST. The counter
no_of_nodes_in_current_level =1 and the level_accessed =1.
3. Access no_of_nodes_in_current_level from the link list. Print the Level Number and
all the data of all the nodes of the current level. Simultaneously add all their children
to the list at the end and keep track of the number of nodes accessed in the next level
in a variable which at the end is assigned back to no_of_nodes_in_current_level.
Also increment level_accessed, indicating one more level accessed in the BST.
4. Continue step 3 repeatedly till no_of_nodes_in_current_level is 0, which means no
more nodes in the next level.

(The above is a non recursive implementation to do level wise printing of the BST. One
could also write a recursive algorithm to do the same.)

14
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:
Simple input of random numbers. Display the height of the tree and the leaf nodes. The
BST entered could be drawn on a rough page and one could check if the height calculated
and the leaf nodes printed are correct.

For eg, Enter : 34, 12, 56, 6, 14, 40, 70.


The height of the BST is 3.
The leaf nodes are 6, 14, 40 and 70.

For Mirror Image:


Enter : 34, 12, 56, 6, 14, 40, 70.

Level wise printing of original tree

Level 1 : 34
Level 2 : 12, 56,
Level 3 : 6, 14, 40, 70

Level wise printing of the mirror tree

Level 1 : 34
Level 2 : 56, 12
Level 3 : 70,40, 14,6

Input :
Enter data ( numbers) to be stored in the binary search tree. Every node in the BST
would contain 3 fields: data, left child pointer and right child pointer

Output
The height of the tree and the list of its leaf nodes.
The original and mirror image printed levelwise.

15
Lab Manual: Data Structures Laboratory

FAQS:

1. How to create the mirror image of the tree?

2. What is the logic for printing the tree level wise ?

3. What is the advantage of creation of the mirror image?

Conclusion:
In this assignment we have studied depth first and breadth first traversal of binary tree
and how to display the tree level-wise. We have also studied how to find out the
mirror image of a tree.

16
Lab Manual: Data Structures Laboratory

Assignment No. 8
Title of Assignment: Creation of binary inorder threaded tree (BST) and perform inorder
traversal using the inorder threads.

Algorithms:

Create and Insert:


1. Accept a random order of numbers from the user. The first number would be inserted
at the root node.
2. Thereafter, every number is compared with the root node. If less than or equal to the
data in the root node, proceed left of the BST, else proceed right.
3. Perform this till you reach a null pointer, the place where the present data is to be
inserted.
4. Allocate a new node and assign the data in this node and allocate pointers
appropriately. Initialize all the thread values to ‘f’ (false).

Creation of Threads :

Could be done in two ways: one after BST is created and the other inserting nodes in the
inorder position of the BST as and when it appears.

1. For the first method, run an inorder traversal (by previous algorithm) and store the
nodes of the inorder traversal as they appear in a linear list.
2. Then read the list of nodes and if a node has its left or right pointer pointing to NULL,
make it now point to the inorder predecessor or successor respectively and assign the
thread values to ‘t’ indicating true. Assign a head node, who will be pointed at by the
left pointer of the 1st node in the inorder traversal and by the right pointer of the last
node in the inorder traversal.

In the other technique, when you want to insert nodes in an existing threaded tree, do the
following :

1. If a node t is to be inserted as the right child of s in a threaded binary tree, t’s right
child will point to s’s right child and so will t’s right thread.
2. t’s left child will point to s and it’s left thread will be assigned ‘t’ (true). s’s right
child will point to t and its right thread will be ‘f’.
3. Find the inorder successor of t and its left child will now point to t.

Inorder travesal using the threads

1. Write a function which will take any node and will give you its inorder successor.
This function will access the right child of the given node.

17
Lab Manual: Data Structures Laboratory

2. If thread value is ‘f’, then as long as left thread is ‘f’ keep moving left through the left
pointer.
3. The node thus finally reached would be the inorder successor.
4. The Inorder traversal now becomes easy : Beginning with the first node of the inorder
traversal, which can be reached from the header node, call the inorder successor
repeatedly, display its data, and go on till you meet the header node again, which
signals the end of the inorder traversal.

Testing:
Test Conditions:
Simple input of random numbers. Display the inorder traversal. It must be a sorted
list of the numbers entered, since a BST has been created. This would be prove that
the threaded BST has been constructed properly

Input:
Enter data (numbers) to be stored in the binary search tree. Every node in the BST would
contain 5 fields: data, left child pointer and right child pointer, left thread tag and a right
thread tag

Output :
Display the list of elements in the serial order as they appear in the inorder traversal.

FAQS:
1. How to create Threaded BST?

2. What is use of Threaded BST?

3. How to travel Treaded BST?

Conclusion:
In this assignment we have studied about threaded binary trees, advantages of
threading and its implementation.

18
Lab Manual: Data Structures Laboratory

Assignment No.9
Title of Assignment: Write a program to represent a graph using adjacency list and
perform BFS and DFS.

Algorithms:

Creation of Adjacency list :


1. Declare an array of pointers to a link list having a data field (to store vertex number)
and a forward pointer. The number of array of pointers would equal the total number
of vertices in the graph.
2. Take the edge set from the user. If for eg, vertex 1 is connected to vertex 2 and 3 in
the graph, the 1st location of the array of pointers (corresponding to vertex 1) would
point to 2 nodes, one having the data 2 (corresponding to vertex 2) and the other
having data 3.
3. In this way construct the entire adjacency list.

DFS (Depth First Search).

1. The start vertex is visited. Next an unvisited vertex w adjacent to v is selected and a
DFS from w initiated.
2. When a vertex u is reached such that all its adjacent vertices have been visited, we
back up to the last vertex visited which has an unvisited vertex w adjacent to it and
initiate a DFS search from w.
3. The search terminates when no unvisited vertex can be reached from any of the
visited ones.

BFS(Breadth First Search).

1. Starting at vertex v and marking it as visited, BFS differs from DFS in that all
unvisited vertices adjacent to v are visited next.
2. Then unvisited vertices adjacent to these vertices are visited and so on.
3. A queue is used to store vertices as they are visited so that later search can be initiated
from those vertices.

19
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:
Enter the graph with 8 vertices and 10 edges (1,2), (1,3), (2,4), (2,5), (3,6), (3,7), (4,8),
(5,8), (6,8),(7,8).

The order of the vertices visited by DFS is : 1, 2, 4, 8, 5, 6, 3, 7.


The order of the vertices visited by BFS is : 1, 2, 3, 4, 5, 6, 7, 8.

Input :
The number of vertices and the edge set of the graph

Output :
The order of vertices visited in both DFS and BFS.

FAQS:

1. What is the time complexity of BFS &DFS Graph?

2. How to create BFS?

3. How to create DFS?

4. What is difference between BFS & DFS?

Conclusion:
In this assignment we have studied how to represent the graph using adjacency list and
DFS and BFS traversals.

20
Lab Manual: Data Structures Laboratory

Assignment No. 10
Title of Assignment: Write a program to represent graph using adjacency list or matrix
and generate minimum spanning tree using PRIM’s algorithm

Algorithms:
Both the methods are implemented using the Greedy approach. The difference lies in the
way the cycle is prevented. To construct a M.S.T. from a graph of n vertices, we need n-
1 edges exactly. Also, these must be selected in a way that the sum of the n-1 edges is
minimum and so cycle is formed.

The Prims method to find the M.S.T is as follows :

1. Start from an arbitrary root vertex, say vertex number 1.


2. Assign two arrays mindist, in which we note the minimum distance from each of the
vertex to vertex 1 and array nearest in which all the vertex are initially near vertex 1.
3. Among mindist find the smallest value and include that vertex in the MST along with
the respective edge. Assign the value in the corresponding nearest entry to –1.
4. Now consider all the other vertices with respect to the vertex recently added to the
MST. If the edge from any of these vertices to the recently added vertex is smaller
than the current value stored in mindist then change the mindist value to this value
and change nearest array value to the recently added node.
5. If n-1 edges are not yet part of the answer goto step 3.
6. The time complexity of the above algorithm is n2, where n is the number of vertices.
There is an outer for loop that loops n-1 times to find the n-1 edges and there is a
inner for loop that scans the mindist array which of size n to find the smallest entry.

The Kruskal’s method to find the M.S.T proceeds in the following manner :

1. Form a min heap of all the edges according to their weights. Any call to delete an
edge from the min heap will return the smallest weighted edge and rearrange the heap
in such a way that the heap property is maintained.
2. Form a list of connected components in which maintain all the vertices in different
sets.
3. Delete the smallest edge from the heap. Check if the two vertices of the edge belong
to different sets; if they do then add the edge to the minimum spanning tree and
merge the sets to which the vertices belong into 1 set.
4. If the two vertices of the set belong to a single set, then do not add the edge to the
MST, in this way cycles are prevented.
5. If n-1 edges do not yet belong to the solution then go back to step 3.
6. The time complexity to sort the edges is aloga, a the number of edges all the other
steps are carried out in a time less than this one. Thus for a sparse graph where a is
approximately equal to n the time complexity is nlogn and for a dense graph where a

21
Lab Manual: Data Structures Laboratory

is approximately equal to n2, the time complexity is n2logn2.


Thus for sparse graphs Kruskal’s algorithm is faster and for a dense graph Prim’s
algorithm is faster.

Testing:
Test Conditions:
The graph for which MST is to be found out is as follows :
Vertex 1 Vertex 2 Edge Weight
1 2 1
2 3 2
1 4 4
2 4 6
2 5 4
3 5 5
3 6 6
4 5 3
5 6 8
4 7 4
5 7 7
6 7 3
The Minimum Spanning Tree for the above graph is
Vertex 1 Vertex 2 Edge Weight

1 2 1
2 3 2
1 4 4
4 5 3
4 7 4
6 7 3

The total weight of the M.S.T is 17.

Input:
Graph entered as an adjacency matrix for n vertices i.e. fill an n*n matrix with the values
of the weights of the edges of the graph where the row number and column number as
the two vertices of one edge.

22
Lab Manual: Data Structures Laboratory

Output :
The Minimum Spanning Tree of the particular graph, i.e. the set of edges which are part
of the M.S.T along with their respective weights and the total weight of the M.S.T.

FAQS:

1. What is the Prim’s algorithm?

2. What Kruskal’s algorithm?

3. What is the diffrence between Prim’s & Kruskal’s algorithm?

Conclusion:
In this assignment we have studied how to represent the graph using adjacency matrix
and finding out MST using Prim’s algorithm.

23
Lab Manual: Data Structures Laboratory

Assignment No. 11
Title of Assignment: Write a C++ Program to create a text file, read it and computer
frequency of vowels, count words, characters, lines and white space
characters and write these results into another text file . Use
command line arguments.

Algorithm:
1. Initialize the variables char_count, word_count, line_count, vowel_count to 0.
2. Accept the name of the text file from the user through command line.
3. Check whether the user has provided the file name through command line. If not
then flag an error and exit.
4. If the user has provided the file name through command line, then store it in a
string.
5. Open the file in read mode.
6. Read the file character by character until end of file is reached.
7. Increment the character count for each and every character.
8. Increment the word count when we encounter space character or new line
character.
9. Increment the vowel count when we get either of a, e, i, o, u, A, E, I, O, U.
10. Increment the line count when we get new line character.
11. Close the opened file.
12. Display the number of characters, words, lines, and vowels in the given text file.

Testing:
Test Conditions:
The text file name is passed as a command line argument. If the file is not present
then the error is reported. If the file is present then the information about the number of
characters, words, lines, and vowels is displayed on the screen.

Input:
The file name is passed as a command line argument.
Output:
The information about the number of characters, words, lines, and vowels is
displayed on the screen.

24
Lab Manual: Data Structures Laboratory

FAQS:

• How to access the command line arguments?


• How to open the files in C++?
• How to read and write the files in C++?
• Which classes support the processing of the files in C++?

Conclusion:

In this assignment we have studied how to process the files in C++ and also we have
studied how to access the command line arguments.

25
Lab Manual: Data Structures Laboratory

Assignment No. 12
Title of Assignment: Write a program to implement direct access file.

Algorithms:

Chaining :
Here we link all the synonyms in the file. Each time we come across a synonym we add
it to empty space in the file and make it’s previous node with same hash key point to it.
So we get different chains of the same synonym in the main file.

Addition of record :
1. Accept record from the user.
2. Calculate hashed value of the key field.
3. Check for that position in the file.
4. If position found empty insert record. If not goto next available location and store
data there.
5. Connect the next pointer of the previous synonym of that key to this location and the
previous pointer of this record to previous synonym.

Searching for a record :


1. Accept the key of record to be searched.
2. Calculate hash value of the key.
3. Check at the position in the file.
4. If not, match found, check for that record in the entire chain by using the next link.
5. If key matched then display the record.
6. If not found, display ‘Record not found’ message.

Deletion of a record :
1. Accept the key field of the record to be deleted.
2. Search the record in the file using the chain.
3. If found, then delete the record by making key = -1.
4. Make the pointer of the previous node point to the next node the current record was
pointing to.
Append a record proceeds similarly as display record, except that after the record is
obtained changes are made to it and written in the same location as was read.

26
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:
Enter any student database with student name, roll number and marks. Use roll
number as key. Display the records to see if they are accessed properly. Delete a
record and then try to display it. Appropriate error message must be printed.

Input:
Student data to be entered in the Simple Index file

Output :
Data displayed on request.

FAQS:
1. What is chaining?

2. What are the types of chaining?

3. How to access data directly by using direct access file?

Conclusion:
In this assignment we have studied various hashing techniques.

27
Lab Manual: Data Structures Laboratory

Assignment No.13
Title of Assignment: Write a program to add binary numbers (assume one bit as one
number) use STL stack.

Algorithms:

Standard Template Library:


Template can be use to create the generic classes and functions that extend
support to generic programming. The collection of the generic classes and functions is
called standard template library.

Components of STL:
1. Containers
2. Algorithms
3. Iterators

Containers:
It is an object that actually stores data. It is the way in which data is stored in
memory. STL containers are implemented by template classes and therefore can be easily
customized to hold different data types.

Algorithm:
An algorithm is a procedure that is used to process data that is held in containers.
STL includes many different types of algorithm.

Iterator:
It is an object that points to an element in a container. We can use an iterator to
more through the contents of a container. Iterators are handled just like like pointers.

Steps:

Accept and convert the no. in binary:-


1. Read numbers
2. Obtain remainder on division by 2
3. Push remainder onto stack
4. Divide no. by 2
5. If no.>0 , goto step 2
6. Display no.
7. return

28
Lab Manual: Data Structures Laboratory

Add:-

1. Initialize carry to zero


2. Pop one element from each stack
3. Add the two and push result into the third stackalso initialise carry caused due to
addition
4. In both stacks are not empty , goto step 2
5. For stack that is not empty , perform addition with carry and push result into the third
stack
6. Convert result intodecimal
7. Return

Testing:
Test Conditions:

Binary value for 7= 111


Binary value for 9= 1001
Result = 16 in binary = 10000

Input:

Enter the no. in decimal

Output :

Output is in decimal as well as in binary

FAQS:

1. What is STL?
2. Why we are using STL?
3. What are the functions used in this program?
4. What is Itrator?
5. What is Container?

Conclusion:
In this assignment we have studied STL and vectors in STL

29
Lab Manual: Data Structures Laboratory

Assignment No.14
Title of Assignment: Write a program to implement Deque using STL

Algorithms:

A deque is double ended queue with optimized operations both at the front and the back
The deque is maintained into standard template library.

Some of the operations that can be performed are:


Front()
Back()
Push_front()
Pop_front()
Push_back()
Pop_back()
Empty()

1. Main()
Read choice from user
2. Switch(choice)
Case 1: read element
Call: push_front(element)
Case 2: read element from user
Call: Push_back()
Case 3: Display front()
Call: pop_front()
Case 4: Display back()
Call: pop_back()
3. If user wants to continue goto step 1
4. Exit

1. Display()
Declare an iterator of the container type . i.e. in this case dequeue say I
For(I=dq.begin();I!=dq.end;i++)
Display(*i)
Return

30
Lab Manual: Data Structures Laboratory

Testing:
Test Conditions:
1. Add from front
2. Add from rear
3. Delete from front
4. Delete from rear

Enter the element to add from front:2


Enter the element to add from front:1
Enter the element to add from rear:4
Enter the element to add from rear:7

The element of the deque are : 1 2 4 7

Delete the element from the front:


Delete the element from the rear:

The element of the deque are : 2 4

Input:
Give the integer input from front and rear. store that data in deque.

Output:
Display the data present in the deque. Display it after deletion of the data from front and
from rear .

FAQS:

1. What are the deque functions declared in the STL?

2. How to use deque functions?

3. What is the use of these deque functions?

Conclusion:
In this assignment we have studied deque in STL

31
Lab Manual: Data Structures Laboratory

Assignment No. 15
Title of Assignment: Write a program to use STL for sorting and searching with user
defined records.

Algorithms:

By including algorithm.h the above file many useful generic algorithms can be applied
on containers. These algorithms can be applied to containers such as list ,vector ,deque,
etc.

Some of the common generic algorithms are available:

Sort: sort the element present in the container class.


Binary_search, search: to search for the element in container class
Equal: to check two containers are equal or not.
Copy: to copy the item of one container class into another container
class.
Fill: to fill all the elements of a container class with a particular item.
Remove: to remove all the elements from the container class

main()

1. Read choice from user


2. Select case choice
Case 1:
Read data from user
Add data to container
Case 2:
Call:display()
Case 3:
Read data to be searched
Declare an iterator of that type
Call: search(start,end,data)
Case 4:
Call: sort(start,end)
3.Exit

32
Lab Manual: Data Structures Laboratory

display()

1. Declare the iterator of the container type , say I


2. For I= begin() ; I not equal to end() ; I++
DISPLAY(*i);
3. Return

Testing:
Test Conditions:

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:1

ENTER ROLL_NO :1
ENTER NAME : A

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:1

ENTER ROLL_NO :2
ENTER NAME : B

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:1

ENTER ROLL_NO :3
ENTER NAME : C

33
Lab Manual: Data Structures Laboratory

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:2


ROLL NO:1
NAME :A

ROLL NO:2
NAME :B

ROLL NO:3
NAME :C

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:3

ENTER ROLL NO :2

THE RECORD WAS FOUND

ROLL NO:2
NAME :B

1. ADD
2. DISPLAY
3. SEARCH
4. SORT
5. EXIT

ENTER YOUR CHOICE:4

ROLL NO:1

34
Lab Manual: Data Structures Laboratory

NAME :A

ROLL NO:2
NAME :B

ROLL NO:3
NAME :C

Input:
Enter the name and roll number of the students.

Output:

Whatever the name and roll number display the records.


Whatever the name and roll number search the records by roll number.
Whatever the name and roll number sort the records by roll number.

FAQS:

1. How to search the records by roll number?

2. How to sort the records by roll number?

Conclusion:
In this assignment we have studied stack in STL

35
Lab Manual: Data Structures Laboratory

Assignment No. 16
Title of Assignment: Mini Project:- Database using sequential files.
Algorithm:

Students will implement mini project in C++ using files

Testing:

Input will be given to test all the cases in the project

FAQS:

Conclusion:

36
Lab Manual: Data Structures Laboratory

37
Lab Manual: Data Structures Laboratory

38
Lab Manual: Data Structures Laboratory

39

You might also like