0% found this document useful (0 votes)
22 views

LABORATORY MANUAL_DS_CI

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

LABORATORY MANUAL_DS_CI

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

DATA STRUCTURE (CSIT 303) LABORATORY

LABORATORY MANUAL

DATA STRUCTURE
(CSIT 303)

III Semester (CSIT)

CHAMELI DEVI GROUP


OF INSTITUTIONS
INDORE (M.P.)

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 1


DATA STRUCTURE (CSIT 303) LABORATORY

DEPARTMENT OF
COMPUTER SCIENCE AND INFORMATION
TECHNOLGY

CERTIFICATE

This is to certify that Mr./Ms………………………………………………………………

with RGTU Enrollment No. 0832 ..…………………………..has satisfactorily completed the

course of experiments in Data structure, as prescribed by Rajiv Gandhi Proudhyogiki

Vishwavidhyalaya, Bhopal for III Semester of the COMPUTER SCIENCE AND

INFORMATION TECHNOLGY during year 2023-24.

Signature of
Faculty In-charge

INDEX

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 2


DATA STRUCTURE (CSIT 303) LABORATORY

S.N. Ex. Name of the Experiment Date of Signature


No. Conduction of Faculty-
in-Charge
Write a program to search an element in the
1 1 array using Linear and Binary Search.
Write a program to perform the following operation
2 2 in Matrix: 1. Addition 2. Subtraction 3.
Multiplication 4. Transpose
Write a program to perform the following
operation on strings using string functions: 1.
3 3
Addition 2. Copying 3. Reverse 4. Length of
String
Write program for implementing the following
sorting methods to arrange a list of integers in
4 4
ascending order: a) Quick sort b) Selection sort c)
Insertion sort d) Merge sort
Write a program that uses stack operations to convert
5 5 a given infix expression into its postfix equivalent
Write a program to merge two sorted array into one
6 6
sorted array.

7 7 Write a program to implement stack using array


and linked list.
Write a program to implement queue and circular
8 8 queue using array.

9 9 Write a program to insert an element in the beginning


and end of singly linked list.

10 10 Write a program to insert an element at any position


in singly and doubly linked list.
Insert and delete a node at any position in doubly
11 11
linked list.
12 12 Write a program of Tower of Hanoi.
Write a program that uses functions to perform the
13 13 following: a) Create a binary search tree of integers.
b) Traverse the above Binary search tree non
recursively in in order.
Ex. No 1 Write a program to search an element in the array using Linear & Binary
Search.

Aim: To understand the concept of Linear Search and binary in an array.


Theory:

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 3


DATA STRUCTURE (CSIT 303) LABORATORY

Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.

Algorithm of linear search


Linear Search (Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Theory:
Techniques for searching an ordered list in which we first check the middle item and - based
on that comparison - "discard" half the data. The same procedure is then applied to the
remaining half until a match is found or there are no more items left.
A binary search halves the number of items to check with each iteration, so locating an item
(or determining its absence) takes logarithmic time. A binary search is a divide and conquer
search algorithm.
Algorithm of binary search
int binary_search(int A[], int key, int imin, int imax)
{
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;
else
{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);
// three-way comparison
if (A[imid] > key)
// key is in lower subset
return binary_search(A, key, imin, imid-1);
else if (A[imid] < key)
// key is in upper subset
return binary_search(A, key, imid+1, imax);
else
// key has been found
return imid;}
}

Viva Questions:

1. What is the running time of linear search, binary search algorithm?


2. What are the advantages of linear search?

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 4


DATA STRUCTURE (CSIT 303) LABORATORY

3. What are the disadvantages of linear search?


4. Write down the algorithm of linear search?
5. What is divide and conquer approach?
6. Write down the names of other algorithms that uses divide and conquer approach.

Ex. No. - 2. Write a program to perform the following operation in Matrix: 1. Addition
2. Subtraction 3. Multiplication 4. Transpose

Aim: To understand the concept of Addition, Subtraction, Multiplication & Transpose


operations on matrix.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 5


DATA STRUCTURE (CSIT 303) LABORATORY

Theory:
Algorithm for Matrix Addition
The addition of two matrices A m*n and Bm*n gives a matrix Cm*n. The elements of C are sum
of corresponding elements in A and B which can be shown as:

for i in 1 to m
for j in 1 to n
cij = aij + bij

Key points:
 Addition of matrices is commutative which means A+B = B+A
 Addition of matrices is associative which means A+(B+C) = (A+B)+C
 The order of matrices A, B and A+B is always same
 If order of A and B is different, A+B can’t be computed
 The complexity of addition operation is O(m*n) where m*n is order of matrices

Algorithm for Matrix Subtraction:-


The subtraction of two matrices Am*n and Bm*n gives a matrix Cm*n. The elements of C are
difference of corresponding elements in A and B which can be represented as:

for i in 1 to m
for j in 1 to n
cij = aij-bij
Key points:
 Subtraction of matrices is non-commutative which means A-B ≠ B-A
 Subtraction of matrices is non-associative which means A-(B-C) ≠ (A-B)-C
 The order of matrices A, B and A-B is always same
 If order of A and B is different, A-B can’t be computed
 The complexity of subtraction operation is O(m*n) where m*n is order of matrices

Theory:
Matrix multiplication falls into two general categories:
 Scalar in which a single number is multiplied with every entry of a matrix
 Multiplication of an entire matrix by another entire matrix will refer to second cate-
gory.
 In the scalar variety, every entry is multiplied by a number, called a scalar.

Matrix C and D below cannot be multiplied together because the number of columns in
C does not equal the number of rows in D. In this case, the multiplication of these two
matrices is not defined

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 6


DATA STRUCTURE (CSIT 303) LABORATORY

Algorithm for matrix multiplication


Matmul(a,b,
m,n,p)
for(i=1 to
m)
for(j = 1 to
p)
c[i][j]=0;
For(k=1 to
n)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
exit
Theory :
A transpose of a matrix is obtained by interchanging rows of the original matrix with
columns and vice-versa.It is very commonly used in mathematics as well as programming
while multiplying two matrices.
Algorithm for matrix transpose:
Declare and initialize a 2-D array p[a][b] of order axb.
Read the matrix p[a][b] from the user.
Declare another 2-dimensional array t to store the transpose of the matrix. This array will
have the reversed dimensions as of the original matrix.
The next step is to loop through the original array and convert its rows to the columns of
matrix t Declare 2 variables i and j.
Set both i , j=0
Repeat until i<b
Repeat until j<a
t[i][j] = p[j][i]
j=j+1**
i=i+1
The last step is to display the elements of the transposed matrix t.

Viva Questions:

1. Define two-dimensional array.


2. Explain row and column major representation of two-dimensional array?
3. Differentiate between one dimensional and two-dimensional array.
4. What is the running time complexity of Matrix Addition?
5. What is the running time complexity of Matrix Subtraction?
6. Consider the two matrices P and Q which are 10 x 20 and 20 x 30 matrices
respectively. What is the number of multiplications required to multiply the two matrices?
7. How to apply transpose operation on matrix?

Ex. No. – 3. Write a program to perform the following operation on strings using string
functions: 1. Addition 2. Copying 3. Reverse 4. Length of String

Aim: To understand the concept of Addition , Copying, Reverse, Length of strings.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 7


DATA STRUCTURE (CSIT 303) LABORATORY

Theory: Strings are used for storing text/characters. For example, "Hello World" is a
string of characters. Unlike many other programming languages, C does not have
a String type to easily create string variables. Instead, you must use the char type and
create an array of characters to make a string in C:

Algorithm of Addition of string:


• Get the two Strings to be concatenated.
• Read string str1, str2 by using %s access specifier.
• use strcat() function.
• strcat(str1, str2)
• After applying strcat() function on both strings string concatenated.
• print first string (appended by second string).

Algorithm of copy of strings:


• Get the two Strings to be copied.
• Read string str1, str2 by using %s access specifier.
• use strcpy() function.
• strcpy(str2,str1)
• After applying strcpy() function on both strings string copied.
• print first string.

Algorithm of Reverse of string:


• Get a String for reverse.
• Read string str1 by using %s access specifier.
• use strrev() function.
• strrev(str1)
• After applying strrev() function on string reversed.
• print reversed string.

Algorithm of length of string:


• Get a String for calculating length of string.
• Read string str1 by using %s access specifier.
• use strlen() function.
• strlen(str1)
• length will be store in variable i ( i=strlen(str1);).
• strlen() function will calculate space also.
• After applying strlen() function on string calculate string length.
• print the string.

Viva Questions:
1. Explain string in c.
2. Explain Addition of strings.
3. Explain the Concept of copy of string.
4. Explain the Concept of reverse of string.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 8


DATA STRUCTURE (CSIT 303) LABORATORY

5. Explain the Concept of length of string.

Ex No. 4. Write program for implementing the following sorting methods to arrange a
list of integers in ascending order: a) Quick sort b) Selection sort c) Insertion sort d)
Merge sort

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 9


DATA STRUCTURE (CSIT 303) LABORATORY

Aim: To understand the concept of quick sort, Selection sort, insertion sort and
merge sort on a list of integers.

Theory:
Insertion sort is an example of an incremental algorithm; it builds the sorted sequence one
number at a time. This is perhaps the simplest example of the incremental insertion
technique, where we build up a complicated structure on n items by first building it on n − 1
items and then making the necessary changes to fix things in adding the last item. The given
sequences are typically stored in arrays. We also refer the numbers as keys. Along with each
key may be additional information, known as satellite data. [Note that "satellite data" does
not necessarily come from satellite!].Since multiple keys with the same value are placed in
the sorted array in the same order that they appear in the input array, Insertion sort is stable.
This algorithm does not require extra memory.
For Insertion sort we say the worst-case running time is θ(n2), and the best-case running time
is θ(n).
Insertion sort use no extra memory it sort in place.
The time of Insertion sort is depends on the original order of an input. It takes a time in Ω(n2)
in the worst-case, despite the fact that a time in order of n is sufficient to solve large instances
in which the items are already sorted.
Algorithm of insertion sort
INSERTION_SORT (A)
FOR j ← 2 TO length[A]
DO key ← A[j]
{Put A[j] into the sorted sequence A[1 . . j − 1]}
i←j−1
WHILE i > 0 and A[i] > key
DO A[i +1] ← A[i]
i←i−1
A[i + 1] ← key

Theory:
Selection sort is not difficult to analyze compared to other sorting algorithms since none of
the loops depend on the data in the array. Selecting the lowest element requires scanning all n
elements (this takes n − 1 comparisons) and then swapping it into the first position. Finding

(n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2 ∈ Θ(n2) comparisons (see arithmetic


the next lowest element requires scanning the remaining n − 1 elements and so on, for

progression). Each of these scans requires one swap for n − 1 elements (the final element is
already in place).

Algorithm of selection sort


void selectionsort(int a[],int n)
BEGIN
int i,j,large,ind;
for(i=n-1;i>0;i--)
DO
large = a[0];
ind = 0;
for(j=1; j<=i; j++)
DO

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 10


DATA STRUCTURE (CSIT 303) LABORATORY

if(a[j]>large)
BEGIN
large = a[j];
ind = j;
END IF
END-FOR
a[ind] = a[i];
a[i] = large;
END-FOR
End
Theory:
Quicksort is a sorting algorithm based on the divide and conquer approach where
An array is divided into subarrays by selecting a pivot element (element selected from the
array).While dividing the array, the pivot element should be positioned in such a way that
elements less than pivot are kept on the left side and elements greater than pivot are on the
right side of the pivot. The left and right subarrays are also divided using the same approach.
This process continues until each subarray contains a single element.
At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.
Time complexity of quick sort for best case and average case is O(n*log n) in worst case
O(n2).

Algorithm of quick sort


QUICKSORT (array A, start, end)
{
1 if (start < end)
2{
3 p = partition(A, start, end)
4 QUICKSORT (A, start, p - 1)
5 QUICKSORT (A, p + 1, end)
6}
}
The partition algorithm rearranges the sub-arrays in a place.
PARTITION (array A, start, end)
{
1 pivot ? A[end]
2 i ? start-1
3 for j ? start to end -1 {
4 do if (A[j] < pivot) {
5 then i ? i + 1
6 swap A[i] with A[j]
7 }}
8 swap A[i+1] with A[end]
9 return i+1
}
Theory:
Merge sort is the sorting technique that follows the divide and conquer approach. It divides
the given list into two equal halves, calls itself for the two halves and then merges the two
sorted halves. We have to define the merge() function to perform the merging.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 11


DATA STRUCTURE (CSIT 303) LABORATORY

Time complexity of merge sort for best case, average case, worst case is O(n*log n) .
Algorithm of Merge Sort

MERGE_SORT(arr, beg, end)


1. if beg < end
2. set mid = (beg + end)/2
3. MERGE_SORT(arr, beg, mid)
4. MERGE_SORT(arr, mid + 1, end)
5. MERGE (arr, beg, mid, end)
6. end of if
END MERGE_SORT

Viva Questions:
1. What is the running time Complexities of insertion sort, quick sort , selection sort, merge
sort in best case?
2. What is the running time Complexity of insertion sort, quick sort , selection sort, merge
sort in worst case?
3. What is the running time Complexity of insertion sort, quick sort , selection sort, merge
sort in average case?
4. Write down the algorithm of insertion sort, quick sort , selection sort, merge sort
5. Write down the advantages & disadvantage of insertion sort, quick sort , selection sort,
merge sort.

Ex. No. 5. Write a program that uses stack operations to convert a given infix
expression into its postfix equivalent.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 12


DATA STRUCTURE (CSIT 303) LABORATORY

Aim: To understand the concept of Conversion of infix expression into postfix


expression equivalent.
Theory:
INFIX: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator in between the two operands. Example: A + B

POSTFIX: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator after (post) its two operands. Example: A B +

Algorithm:
1.Scan the infix expression from left to right.
2.If the scanned character is an operand, put it in the postfix expression.
3.Otherwise, do the following
3.1 If the precedence and associativity of the scanned operator are greater than the
precedence and associativity of the operator in the stack [or the stack is empty or the stack
contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is right associative and other
operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
3.1.1Check especially for a condition when the operator at the top of the stack and the
scanned operator both are ‘^‘. In this condition, the precedence of the scanned operator is
higher due to its right associativity. So it will be pushed into the operator stack.
3.1.2In all the other cases when the top of the operator stack is the same as the scanned
operator, then pop the operator from the stack because of left associativity due to which the
scanned operator has less precedence.
3.2 Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator.
3.2.1 After doing that Push the scanned operator to the stack. (If you encounter parenthesis
while popping then stop there and push the scanned operator in the stack.)
4.If the scanned character is a ‘(‘, push it to the stack.
5.If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6.Repeat steps 2-5 until the infix expression is scanned.
7.Once the scanning is over, Pop the stack and add the operators in the postfix expression
until it is not empty.
8.Finally, print the postfix expression.

Viva questions:
1. What is Infix expression ?
2. What is Postfix expression?
3. What is operator and operands?
4. Rules of conversion infix into postfix?
5. Which operator has highest, lowest precedence?

Ex. No. 6. Write a program to merge two sorted array into one sorted array.

Aim: To understand the concept of Merging two sorted array into one sorted array.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 13


DATA STRUCTURE (CSIT 303) LABORATORY

Theory:
An array is a collection of items of same data type stored at contiguous memory locations.
Merging the two sorted array first need two arrays which is already sorted combine them in
third array and apply any sort algorithm.

Algorithm:
1. start the program
2. input the length of both the arrays.
3. Input the arrays elements from user.
4. Copy the elements of the first array to the merged array when initializing it.
5. Copy the elements of the second array to the merged array while initializing the
second array.
6. Sort the merged array now.
7. Display the merged array.
8. The program ends here.

Viva questions:
1. What is array ?
2. What is sorting?
3. What is merging?
4. How to declare arrays?

Ex No 7. Write a program to implement stack using array and linked list.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 14


DATA STRUCTURE (CSIT 303) LABORATORY

Aim: To understand the concept of stack and learn the implementation of stack using
array and linked list.
Theory:
A stack is a container of objects that are inserted and removed according to the last-in first-
out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the
item into the stack, and pop the item out of the stack. A stack is a limited access data
structure - elements can be added and removed from the stack only at the top. Push adds
an item to the top of the stack, pop removes the item from the top. A helpful analogy is to
think of a stack of books; you can remove only the top book, also you can add a new book
on the top.

Algorithm for Push Operation


begin procedure push: stack, data if stack is full
return null
end if
top ← top + 1
stack[top] ← data
end procedure

Algorithm for Pop Operation


begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1 return data
end procedure

Viva Questions:-
1. What is a stack?
2. What is array?
3. What is linked list?
4. What are the applications of stack?
5. Explain push algorithm of stack?
6. Explain pop algorithm of stack?
7. Why stack is known as LIFO?

Ex No. 8 Write a program to implement queue and circular queue using array.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 15


DATA STRUCTURE (CSIT 303) LABORATORY

Aim: To understand the concept of insertion & deletion operation in a queue


Theory:
A queue is an ordered collection of items where the addition of new items happens at one
end, called the “rear,” and the removal of existing items occurs at the other end, commonly
called the “front.” As an element enters the queue it starts at the rear and makes its way
toward the front, waiting until that time when it is the next element to be removed.
The most recently added item in the queue must wait at the end of the collection. The item
that has been in the collection the longest is at the front. This ordering principle is sometimes
called FIFO, first-in first-out. It is also known as “first-come first-served.

Simple queue:
Insertion operation: enqueue(): The enqueue() is a data manipulation operation that is used
to insert elements into the stack. The following algorithm describes the enqueue() operation
in a simpler way.
Algorithm:
1 − START
2 – Check if the queue is full.
3 − If the queue is full, produce overflow error and exit.
4 − If the queue is not full, increment rear pointer to point the next empty space.
5 − Add data element to the queue location, where the rear is pointing.
6 − return success.
7 – END
Deletion Operation: dequeue(): The dequeue() is a data manipulation operation that is used
to remove elements from the stack. The following algorithm describes the dequeue()
operation in a simpler way.
Algorithm:
1 – START
2 − Check if the queue is empty.
3 − If the queue is empty, produce underflow error and exit.
4 − If the queue is not empty, access the data where front is pointing.
5 − Increment front pointer to point to the next available data element.
6 − Return success.
7 – END
Circular Queue:
Algorithm for insertion in queue
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure

Algorithm for deletion in queue


procedure dequeue
if queue is empty return underflow
end if

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 16


DATA STRUCTURE (CSIT 303) LABORATORY

data = queue[front]
front ← front + 1
return true
end procedure

Viva Questions:
1. What is queue?
2. Types of queue?
3. Explain Operations in queue?
4. How to insert and delete the elements in simple queue?
5. How to insert and delete the elements in circular queue?

Ex. No. 9 Write a program to insert an element in the beginning and end of singly
linked list.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 17


DATA STRUCTURE (CSIT 303) LABORATORY

Aim: To understand the concept of Singly Link List and implement a program for
Insertion operations.
Theory:
Linked list is a collection of Nodes. Each node having two parts. First part represents
value of the node and second part represents an address of the next node. If Next node is
not present then it contains NULL value.

Consider Following Presentation of Linked List:

In above presentation FIRST is a pointer which always contains an address of first


node in the linked list. If linked list is empty then value of FIRST pointer is NULL.
In Linked List nodes are logically adjacent but physically not adjacent to each other.
Because address of first node is 2000, address of second node is 2010 and address of
third node is 2002.

Algorithm of Insertion:-
In a singly linked list, the insertion operation can be performed in three ways. They are as
follows:-
 Insertion at Beginning of the list
 Insertion at End of the list
 Insertion at Specific location in the list

Insertion at Beginning of the list


Step 1: Create a newNode with given value.
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set newNode→next = NULL and head = newNode.
Step 4: If it is Not Empty then, set newNode→next = head and head = newNode.

Insertion at End of the list


Step 1: Create a newNode with given value and newNode → next as NULL.
Step 2: Check whether list is Empty (head == NULL).
Step 3: If it is Empty then, set head = newNode.
Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5: Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next is equal to NULL).
Step 6: Set temp → next = newNode.

Viva Questions:-
1. What is singly linked list?
2. What are the advantages of singly linked list?

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 18


DATA STRUCTURE (CSIT 303) LABORATORY

3. What are the applications of singly linked list?


4. What is the condition for linked list Overflow & Underflow?
5. How linked list is represented in memory?

Ex. No.10 Write a program to insert an element at any position in singly and doubly
linked list.

Aim: To understand the concept of insert an element at any position in singly and
doubly linked list.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 19


DATA STRUCTURE (CSIT 303) LABORATORY

Theory:
Inserting At Specific location in singly linked list (After a Node)
Step 1: if ptr = null(write overflow goto step 12 end of if)
Step 2: set new_node = ptr
Step 3: new_node → data = val
Step 4: set temp = head
Step 5: set i = 0
Step 6: repeat step 5 and 6 until i<loc< li=""></loc<>
Step 7: temp = temp → next
Step 8: if temp = null(write “desired node not present” goto step 12 ,end of if, end of loop)
Step 9: ptr → next = temp → next
Step 10: temp → next = ptr
Step 11: set ptr = new_node
Step 12: exit

Inserting at specific location in the doubly linked list (After a Node)


Step 1: if ptr = null (write overflow and Go to step 15 [end of IF])
Step 2: set new_node = ptr
Step 3: set ptr = ptr -> next
Step 4: set new_node -> data = val
Step 5: set temp = start
Step 6: set i = 0
Step 7: repeat 8 to 10 until i<="" li="">
Step 8: set temp = temp -> next
Step 9: if temp = null
Step 10: write "less than desired no. of elements" (Goto Step 15 [end of IF] [end of Loop]).
Step 11: set new_node -> next = temp -> next
Step 12: set new_node -> prev = temp
Step 13 : set temp -> next = new_node
Step 14: set temp -> next -> prev = new_node
Step 15: exit

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 20


DATA STRUCTURE (CSIT 303) LABORATORY

Viva Questions:
1. Explain singly linked list.
2. Explain doubly linked list.
3. Insert an element in singly linked list after a specific location and node.
4. Insert an element in doubly linked list after a specific location and node.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 21


DATA STRUCTURE (CSIT 303) LABORATORY

Ex. No. 11. Insert and delete a node at any position in doubly linked list.

Aim: To understand the concept of insertion and deletion a node at any position in
doubly linked list.
Theory :
Algorithm :
Insertion
Step 1: if ptr = null (write overflow and Go to step 15 [end of IF])
Step 2: set new_node = ptr
Step 3: set ptr = ptr -> next
Step 4: set new_node -> data = val
Step 5: set temp = start
Step 6: set i = 0
Step 7: repeat 8 to 10 until i<="" li="">
Step 8: set temp = temp -> next
Step 9: if temp = null
Step 10: write "less than desired no. of elements" (Goto Step 15 [end of IF] [end of Loop]).
Step 11: set new_node -> next = temp -> next
Step 12: set new_node -> prev = temp
Step 13 : set temp -> next = new_node
Step 14: set temp -> next -> prev = new_node
Step 15: exit
Deletion
1.If the head of the list is NULL, that means the list is empty or if Nnext), now the next node
of del has become pointer_to_head** node.
2.Check if the node to be deleted is not the first node, then update next of the previous node
of del del->prev->next = del->next.
3.Also check, if the node to be deleted is not the last, then update the prev pointer of the next
node of del del->next->prev = del->prev and delete the del node.
4.Finally, output the desired linked list.

Viva Questions:
1. Explain doubly linked list.
2. Insert an node in doubly linked list after a specific location.

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 22


DATA STRUCTURE (CSIT 303) LABORATORY

Ex. No. – 12. Write a program of Tower of Hanoi.

Aim: To understand the concept of Tower of Hanoi.


Theory: It is a classic problem where you try to move all the disks from one peg to another
peg using only three pegs. Initially, all of the disks are stacked on top of each other with
larger disks under the smaller disks. You may move the disks to any of three pegs as you
attempt to relocate all of the disks, but you cannot place the larger disks over smaller disks
and only one disk can be transferred at a time. Tower of Hanoi is a mathematical puzzle
where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in
decreasing value of diameter i.e., the smallest disk is placed on the top and they are on
rod A. The objective of the puzzle is to move the entire stack to another rod (here
considered C), obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a
stack.
3. No disk may be placed on top of a smaller disk.
Time complexity: O(2N), There are two possibilities for every disk. Therefore, 2 * 2 * 2
* . . . * 2(N times) is 2 Nw . To write an algorithm for Tower of Hanoi, first we need to learn
how to solve this problem with lesser number of disks, say → 1 or 2. We mark three towers
with name, source, destination and aux (only to help moving the disks). If we have only one
disk, then it can easily be moved from source to destination peg.If we have 2 disks −
 First, we move the smaller (top) disk to aux peg.
 Then, we move the larger (bottom) disk to destination peg.
 And finally, we move the smaller disk from aux to destination peg.
 The steps to follow are −
 Step 1 − Move n-1 disks from source to aux
 Step 2 − Move nth disk from source to dest
 Step 3 − Move n-1 disks from aux to dest
 A recursive algorithm for Tower of Hanoi can be driven as follows –

1. START
2. Procedure Hanoi(disk, source, dest, aux)
3. IF disk == 1, THE
4. move disk from source to dest
5. ELSE
6. Hanoi(disk - 1, source, aux, dest) // Step 1
7. move disk from source to dest // Step 2
8. Hanoi(disk - 1, aux, dest, source) // Step 3
9. END IF
10. END Procedure
11. STOP

Viva Questions:
1. What is the objective of tower of hanoi puzzle?
2. What is time complexity of the solution tower of hanoi problem using recursion ?
3. Minimum number of moves required to solve a tower of hanoi problem with n disks ?
4. Space complexity of recursive solution of tower of hanoi puzzle .

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 23


DATA STRUCTURE (CSIT 303) LABORATORY

Ex. No.13. Write a program that uses functions to perform the following: a) Create a
binary search tree of integers. b) Traverse the above Binary search tree non recursively
in in order

Aim: To understand the concept of binary search tree .


Theory: A binary search tree is a type of tree data structure that enables users to sort and
store information. Because each node can only have two children, it is known as a binary
tree. It is also known as a search tree because we can look up numbers in O(log(n)) time. The
root node is greater than all nodes in the left subtree.The root node is outperformed in value
by every node in the right subtree.Each node's two subtrees are likewise binary search trees,
therefore they have the aforementioned two characteristics.

Algorithm:
struct node* newNode(int item) {
struct node* temp = (struct node*) malloc (sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp; }

Algorithm to Traverse binary search tree with no recursion in in-order:


1. Initialize current as root
2. While current is not NULL
If the current does not have left child
a) Print current’s data
b) Go to the right, i.e., current = current->right
Else
a) Find rightmost node in current left subtree OR
node whose right child == current.
If we found right child == current
a) Update the right child as NULL of that node whose right child is current
b) Print current’s data
c) Go to the right, i.e. current = current->right
Else
a) Make current as the right child of that rightmost
node we found; and
b) Go to this left child, i.e., current = current->left

Viva Questions:
1.Explain binary search tree?
2.How to create a binary search tree?
3.Advantages of binary search tree?
4.Disadvantages of binary search tree?
5.Time and space complexity of creating, inserting, deleting, searching a node in binary
search tree?
6.How to traverse the binary search tree?

DEPARTMENT OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY 24

You might also like