You are on page 1of 115

Geethanjali College of Engineering and Technology

(UGC AUTONOMOUS INSTITUTION)


(Accredited by NBA and NAAC with ‘A’ grade, Approved by AICTE New Delhi and Affiliated to JNTUH)
Cheeryal (V), Keesara (M), Medchal (Dist), Telangana – 501 301.

Data Structures
II Year I Semester (AR20)
(B.Tech-CSE, B.Tech-CSE (AI&ML), B.Tech-CSE (DS), B.Tech-CSE (CS), B.Tech-CSE (IOT))
Laboratory Work Book
(20CS20L01)

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING,
CSE-AIML,DS,CS & IOT
(2023-2024)

Lab-In Charge HoD

Geethanjali College of Engineering and Technology Page 1


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 2


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology


(UGC Autonomous)
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T.S)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING, CSE-AIML,DS,CS & IOT

DATA STRUCTURES
LABORATORY WORKBOOK

Name :_____________________________________

Roll No :____________ Class:________Branch:_________

Academic Year : 20____- 20____

Geethanjali College of Engineering and Technology Page 3


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology


(UGC Autonomous)
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T.S)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Geethanjali College of Engineering and Technology Page 4


Data Structures Lab Dept. of CSE.

CSE-AIML,DS,CS & IOT

CERTIFICATE
This is to certify that Mr./ Ms. _________________________________has
satisfactorily completed ________ number of experiments in the Data Structures
Laboratory.

Roll No: ____________ Branch: _______________

Year: ______________ Academic Year: ______________

Head of the Dept FacultyIn charge

Internal Examiner External Examiner

Geethanjali College of Engineering and Technology Page 5


Data Structures Lab Dept. of CSE.

LIST OF EXPERIMENTS

Geethanjali College of Engineering and Technology Page 6


Data Structures Lab Dept. of CSE.

DATA STRUCTURES LAB


S.N Name of the Program Page
o. no
1 Write a C program for polynomial addition using linked lists. 12

2 Write a C program that uses functions to perform the following: 19


a) Create circularly linked lists
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
3 Write a C program that uses functions to perform the following: 25
a) Create a doubly linked list of integers.
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
4 Write C programs to implement a Stack and Queue ADT using 33
singly linked list.

5 Write a C program to implement the following: 44


a) Towers of Hanoi.
b) Parenthesis Checker (by using stack).

6 Write a C program to implement Circular Queue using array. 49


7 Write C programs to implement a double ended queue ADT using linked list. 54
8 Write a C program that uses functions to perform the following: 59
i) Create a binary search tree of integers.
ii) Traverse the above Binary search tree in in-order, pre-order,
post-order.
9 Write C programs for implementing the following sorting methods to arrange a 64
list of integers in ascending order:
a) Merge sort. b) Heap sort.

10 Write C programs for implementing the following sorting methods to arrange a 69


list of integers in ascending order:
a) Radix sort. b) Binary Insertion sort.

11 Write a C program to perform the following operation (B-tree-> Balanced tree) 75


a) Insertion into a B-tree. b) Searching a B-Tree.

Geethanjali College of Engineering and Technology Page 7


Data Structures Lab Dept. of CSE.

12 Write C programs for implementing the following graph traversal algorithms: 82


a) Depth first traversal. b)Breadth first traversal.

13 Write a C program to implement all the functions of a dictionary (ADT) using 87


hashing.

14 Write a C program for pattern matching using Knuth-Morris-Pratt algorithm. 93

ADDITIONAL PROGRAMS

Geethanjali College of Engineering and Technology Page 8


Vision of the Institute
Geethanjali visualizes dissemination of knowledge and skills to students, who eventually
contribute to well being of the people of the nation and global community.

Mission of the Institute

● To impact adequate fundamental knowledge in all basic science and engineering


technical and Inter-Personals skills so students.

● To bring out creativity in students that would promote innovation, research and
entrepreneurship

● To Preserve and promote cultural heritage, humanistic and spiritual values promoting
peace and harmony in society

Vision of the Department


To produce globally competent and socially responsible computer science engineers contributing
to the advancement of engineering and technology which involves creativity and innovation by
providing excellent learning environment with world class facilities.

Mission of the Department

1. To be a center of excellence in instruction, innovation in research and scholarship, and


service to the stake holders, the profession, and the public.

2. To prepare graduates to enter a rapidly changing field as a competent computer science


engineer.

3. To prepare graduate capable in all phases of software development, possess a firm


understanding of hardware technologies, have the strong mathematical background
necessary for scientific computing, and be sufficiently well versed in general theory to
allow growth within the discipline as it advances.

4. To prepare graduates to assume leadership roles by possessing good communication


skills, the ability to work effectively as team members, and an appreciation for their
social and ethical responsibility in a global setting.

Geethanjali College of Engineering and Technology Page 1


Data Structures Lab Dept. of CSE.

PEO’s, PO’s & PSO’s


PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)
CSE & CSE (AI&ML,DS,CS,IOT)
1. To provide graduates with a good foundation in mathematics, sciences and engineering
fundamentals required to solve engineering problems that will facilitate them to find
employment in industry and / or to pursue postgraduate studies with an appreciation for
lifelong learning.

2. To provide graduates with analytical and problem-solving skills to design algorithms,


other hardware / software systems, and inculcate professional ethics, inter-personal skills
to work in a multi-cultural team.

3. To facilitate graduates to get familiarized with the art software / hardware tools, imbibing
creativity and innovation that would enable them to develop cutting-edge technologies of
multi-disciplinary nature for societal development.

PROGRAM OUTCOMES (Common to all branches)


Engineering Graduates would be able to:
1. PO 1:Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. PO 2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3. PO 3: Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

Geethanjali College of Engineering and Technology Page 2


Data Structures Lab Dept. of CSE.

4. PO 4: Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

5. PO 5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.

6. PO 6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

7. PO 7: Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

8. PO 8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9. PO 9: Individual and teamwork: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

10. PO 10: Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

11. PO 11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

12. PO 12: Life-long learning: Recognize the need for and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change..

Geethanjali College of Engineering and Technology Page 3


Data Structures Lab Dept. of CSE.

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE)

PSO 1: Demonstrate competency in Programming and problem-solving skills and apply


these skills in solving real world problems
PSO 2: Select appropriate programming languages, Data structures and algorithms in
combination with modern technologies and tools, apply them in developing creative and
innovative solutions
PSO 3: Demonstrate adequate knowledge in emerging technologies

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE-AI&ML)

PSO 1: Demonstrate competency in Programming and problem-solving skills and apply


those skills in solving computing problems
PSO 2: Select appropriate programming languages, Data structures and algorithms
combination with modern technologies and apply them in developing innovative
solutions
PSO 3: Demonstrate adequate knowledge in the concepts and techniques of artificial
intelligence and machine learning, apply them in developing intelligent systems to solve
real world problems

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE-DS)

PSO 1: Demonstrate competency in Programming and problem-solving skills and apply


those skills in solving computing problems.
PSO 2: Select appropriate programming languages, Data structures and algorithms in
combination with modern technologies and apply them in developing innovative solutions.
PSO 3: Apply techniques of data modelling, analysis and visualization which include

Geethanjali College of Engineering and Technology Page 4


Data Structures Lab Dept. of CSE.

statistical techniques to solve real world problems delivering actionable insights for
decision making.

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE-CS)

PSO 1: Demonstrate competency in Programming and problem-solving skills and apply


those skills in solving computing problems.
PSO 2: Select appropriate programming languages, Data structures and algorithms in
combination with modern technologies and apply them in developing innovative solutions.
PSO 3: Apply cryptographic algorithms for ensuring cyber security as per cyber laws,
demonstrate awareness of all the security related issues and employ state of the art
technologies to protect the digital assets of an organization.

PROGRAM SPECIFIC OUTCOMES (PSO’s) - (CSE-IoT)

PSO 1: Demonstrate competency in Programming and problem-solving skills and apply those
skills in solving computing problems.
PSO 2: Select appropriate programming languages, Data structures and algorithms in
combination with modern technologies and apply them in developing innovative solutions.
PSO 3: Demonstrate an ability in using IoT devices and protocols to develop IoT based
solutions for real world problems.

Geethanjali College of Engineering and Technology Page 5


Data Structures Lab Dept. of CSE.

Course Objectives:
Develop ability to
1. Understand the basic concepts of Abstract Data Types, Linear and Non-Linear Data
structures.
2. Identify the notations used to represent the Performance of algorithms.
3. Understand the behavior of data structures such as stacks, queues, trees, hash tables, search
trees, Graphs and their representations.
4. Familiarize with various data structures for various applications.
5. Understand various searching and sorting algorithms.
6. Write programs in C to solve problems using data structures such as arrays, linked lists,
stacks, queues, trees, graphs, hash tables and search trees.

Course Outcomes:
Upon successful completion of this course, students will be able to:

CO1. Use asymptotic notation in representing space and time complexities of algorithms.
CO2. Construct different linear and non-linear data structures using array and linked
representations and use them in appropriate applications.
CO3. Implement, use and compare different sorting, searching and pattern-matching
algorithms for solving various problems.

Mapping of Lab Course with Programme Educational Objectives

S.No Course code course Semester PEO 1 PEO 2 PEO 3


component
Professional II year I
1 20CS21L01 DS Lab Semester
1 2 -
core

Geethanjali College of Engineering and Technology Page 6


Data Structures Lab Dept. of CSE.

Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes-
CSE,CSE(AI & ML), CSE (DS),CSE(CS),CSE(IOT):

POs 1 2 3 4 5 6 7 8 9 10 11 12 PS PS
O1 O2
DS Lab Exp
no.
CO1:Use 1,2,3,4 3 2 3 1 1 1 2 2 3
asymptotic ,5,6,7,
notation in 8,9,10,
representing space 11,12,
and time 13.
complexities of
algorithms.

CO2:Construct 1,2,3,4 2 2 2 3 1 1 2 2 1
different linear ,5,6,7,
and non-linear 8,9,10,
data structures 11,12,
using array and 13.
linked
representations
and use them in
appropriate
applications.

CO3:Implement, 7,8,9, 2 2 2 3 1 1 2 2 1
use and compare 10,11,
different sorting, 12,13.
searching and
pattern-matching
algorithms for
solving various
problems.

Prerequisites:
20CS11L1 Programming for Problem Solving-I LAB

Geethanjali College of Engineering and Technology Page 7


Data Structures Lab Dept. of CSE.

20CS12L1 Programming for Problem Solving-II LAB

INSTRUCTIONS TO THE STUDENTS:

1. Students are required to attend all labs.


2. Students should be dressed in formals when attending the laboratory sessions.
3. Students will work individually in computer laboratories.
4. While coming to the lab bring the observation book and Work book etc.
5. Before coming to the lab, prepare the pre-lab questions. Read through the lab
experiment to familiarize you.
6. Utilize 3 hours time properly to perform the experiment and noting down the outputs.
7. If the experiment is not completed in the prescribed time, the pending work has to be
done in the leisure hour or extended hours.
8. You will be expected to submit the completed work book according to the deadlines
set up by your instructor.

INSTRUCTIONS TO LABORATORY TEACHERS:

1. Observation book and lab records submitted for the lab work are to be checked and
signed before the next lab session.
2. Students should be instructed to switch ON the power supply after the connections
are checked by the lab assistant / teacher.
3. The promptness of submission should be strictly insisted by awarding the marks
accordingly.
4. Ask Discussion Topics at the end of the experiment.
5. Do not allow students who come late to the lab class.
6. Encourage the students to do the experiments innovatively.
7. Fill continuous Evaluation sheet, on regular basis.
8. Ensure that the students are dressed in formals.

Scheme of Lab Exam Evaluation:


Evaluation of Internal Marks:

Geethanjali College of Engineering and Technology Page 8


Data Structures Lab Dept. of CSE.

a) Write-up on Day to day Record and Observation book ----------- 10 Marks

b) Viva-voce/tutorial/case study/poster presentation--------------------10 Marks

c) Internal laboratory test —------------------------------------------------10 Marks


1) Write up and program---------5 Marks
2) Execution of Program ---------5 Marks
d) Laboratory Project—------------------------------------------------------10 Marks

Evaluation of External Marks:


60 marks are awarded for conducting laboratory test as follows:
1) Write-up Algorithm—------------------------------10Marks.

2) Experiment/program------------------------------- 15 Marks

3) Execution of Program —--------------------------- 15 Marks

4) Presentation on another experiment/program—--10 Marks

5) Viva-voce —------------ ----------------------------- 10 Marks

Geethanjali College of Engineering and Technology Page 9


Data Structures Lab Dept. of CSE.

INDEX
Date of
Date of Mark Signatur Rema
S.No Name of Experiment Submis
Exp. s e rks
sion

Geethanjali College of Engineering and Technology Page 10


Data Structures Lab Dept. of CSE.

INDEX
Date of
Date of Mark Signatur Rema
S.No Name of Experiment Submis
Exp. s e rks
sion

Geethanjali College of Engineering and Technology Page 11


Data Structures Lab Dept. of CSE.

WEEK 1 Date:
Write a C program for polynomial addition using linked lists.

Objectives:
Student will able to learn the practical application of linear list.

ALGORITHM/PSEUDOCODE:
Step 1: Start
Step 2: Let p and q be the two polynomials represented by the linked list.
Step 3: While p and q are not null, repeat step 2.
Step 4: Sort both polynomial
Step 5: If powers of the two terms are equal then if the terms do not cancel then insert the sum of
the terms into the sum Polynomial
Step 5.1: Advance p
Advance q
Step 5.2: Else if the power of the first polynomial> power of second
Step 4.2.1: Then insert the term from first polynomial into sum polynomial
Step 4.2.2: Advance p
Step 5.3: Else insert the term from second polynomial into sum polynomial
Advance q
Step 6: Copy the remaining terms from the non empty polynomial into the sum polynomial
Step 7: Stop.

Geethanjali College of Engineering and Technology Page 12


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 13


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 14


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 15


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 16


Data Structures Lab Dept. of CSE.

Input Output

Outcomes:
The student will be able to understand the requirements of a mathematical problem and develop
a solution using appropriate data structure.

Geethanjali College of Engineering and Technology Page 17


Data Structures Lab Dept. of CSE.

DISCUSSION TOPICS

1. What are the applications of linked list?

2. What are the reasons for choosing linked list to solve polynomial addition?

WEEK 2 Date:

Write a C program that uses functions to perform the following:


a. Create circularly linked lists
b. Delete a given integer from the above linked list.
c. Display the contents of the above list after deletion.

Objectives:
Student will able to learn the implementation of circularly linked list Data structure.

ALGORITHM/PSEUDOCODE:
Step 1: Start
Step 2: Creation: Get the number of elements, and create the nodes having fields DATA and
LINK and store the element in Data field, link them together to form a linked list where the
last node always contains the address of first node .
Step 3: Insertion: Get the number to be inserted and create a new node, store the value in
DATA field. And insert the node in the required position .If it is last node make sure it
contains the address of first node.
Step 4: Deletion: Get the number to be deleted. Search the list from the beginning and locate
the node then delete the node.
Step 5: Display: Display all the nodes in the list.
Step 6: Stop.

Geethanjali College of Engineering and Technology Page 18


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 19


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 20


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 21


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 22


Data Structures Lab Dept. of CSE.

Outcomes:

Geethanjali College of Engineering and Technology Page 23


Data Structures Lab Dept. of CSE.

Student gains the ability


● To understand the Circularly linked list Data structure.

● To differentiate between different types of linear lists

● To implement the various operations of circularly linked list.

DISCUSSION TOPICS

1. Explain the limitation of linear linked list.

2. What is the importance of circular linked list?

3. What is abstract Data Type?

WEEK 3 Date:

Write a C program that uses functions to perform the following:


a. Create a doubly linked list of integers.

Geethanjali College of Engineering and Technology Page 24


Data Structures Lab Dept. of CSE.

b. Delete a given integer from the above doubly linked list.


c. Display the contents of the above list after deletion.

Objectives:
Student will able to learn the implementation of doubly linked list Data structure.

ALGORITHM/PSEUDOCODE:

Inserting At Beginning of the list


Step 1 -Create anewNodewith given value andnewNode previousasNULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 -If it isEmptythen, assignNULLtonewNode next and newNode to head.
Step 4 -If it isnot Emptythen, assignheadtonewNode next and newNode to head.

Inserting At End of the list


Step 1 -Create anewNodewith given value andnewNode nextasNULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 -If it isEmpty, then assignNULLtonewNode previousandnewNodetohead.
Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.
Step 5 -Keep moving thetempto its next node until it reaches to the last node in the list (untiltemp nextis equal to

Step 6 -AssignnewNodetotemp nextandtemptonewNode previous.

Inserting At Specific location in the list (After a Node)


Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 -If it isEmptythen, assignNULLto bothnewNode previous&newNode nextand setnewNodetohead.
Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and
initialize temp1 with head.

Step 5 -Keep moving thetemp1to its next node until it reaches to the node after which we want to insert the newN

Step 6 - Every time check whether temp1 is reached to the last node. If it is reached to the last
node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate
the function. Otherwise move the temp1 to next node.
Step 7 -Assigntemp1 nexttotemp2,newNodetotemp1 next,temp1tonewNode previous,temp2tonewNode nextan

Geethanjali College of Engineering and Technology Page 25


Data Structures Lab Dept. of CSE.

Deleting from Beginning of the list


Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 -Check whether list is having only one node (temp previousis equal totemp next)
Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions)
Step 6 -If it isFALSE, then assigntemp nexttohead,NULLtohead previousand deletetemp.

Deleting from End of the list


Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 -Check whether list has only one Node (temp previousandtemp nextboth areNULL)
Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate from the
function. (Setting Empty list condition)
Step 6 -If it isFALSE, then keep movingtempuntil it reaches to the last node in the list. (untiltemp nextis equal t

Step 7 -AssignNULLtotemp previous nextand deletetemp.

Displaying a Double Linked List


Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4 - Display 'NULL <--- '.
Step 5 -Keep displayingtemp datawith an arrow (<===>) untiltempreaches to the last node

Step 6 -Finally, displaytemp datawith arrow pointing toNULL(temp data ---> NULL).

Geethanjali College of Engineering and Technology Page 26


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 27


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 28


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 29


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 30


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 31


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the ability
● To understand the doubly linked list Data structure.

● To differentiate between different types of linear lists

● To implement the various operations of doubly linked list.

DISCUSSION TOPICS

1. Write the syntax of a node in doubly linked list?

2. What the difference is between singly linked and doubly linked list?

3. List the advantages of doubly linked list over singly linked list?

Geethanjali College of Engineering and Technology Page 32


Data Structures Lab Dept. of CSE.

WEEK 4: Date:

Write C programs to implement a Stack and Queue ADT using Singly Linked List.
Objectives:
Student will able to learn the explicit implementation of lists namely Stack and Queue.
Algorithm: Stack Using Linked List

To implement stack using linked list, we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all the user
defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define a Node pointer 'top' and set it to NULL.
Step 4: Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.

push(value) - Inserting an element into the Stack


We can use the following steps to insert a new node into the stack…
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode next = NULL.
Step 4: If it is Not Empty, then set newNode next = top.
Step 5: Finally, set top = newNode.

pop() - Deleting an Element from a Stack


We can use the following steps to delete a node from the stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate
the function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top next'.
Step 7: Finally, delete 'temp' (free(temp)).

display() - Displaying stack of elements


We can use the following steps to display the elements (nodes) of a stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.

Geethanjali College of Engineering and Technology Page 33


Data Structures Lab Dept. of CSE.

Step 4: Display 'temp data --->' and move it to the next node. Repeat the same until temp reaches to the first nod

Step 5: Finally! Display 'temp data ---> NULL'.

Program

Geethanjali College of Engineering and Technology Page 34


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 35


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 36


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 37


Data Structures Lab Dept. of CSE.

Algorithm/Pseudocode: Queue Using Linked List

Step 1: Include all the header files which are used in the program. And declare all the user
defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4: Implement the main method by displaying Menu of list of operations and make suitable
function calls in the main method to perform user selected operation.

enQueue(value) - Inserting an element into the Queue


Step 1: Create a newNode with given value and set 'newNode next' to NULL.
Step 2: Check whether queue is Empty (rear == NULL)
Step 3: If it is Empty then, set front = newNode and rear = newNode.
Step 4: If it is Not Empty then, set rear next = newNode and rear = newNode.

deQueue() - Deleting an Element from Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate
from the function
Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4: Then set 'front = front next' and delete 'temp' (free(temp)).

display() - Displaying the elements of Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4: Display 'temp data --->' and move it to the next node. Repeat the same until 'temp' reaches to 'rear' (temp

Step 5: Finally! Display 'temp data ---> NULL'.

Program

Geethanjali College of Engineering and Technology Page 38


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 39


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 40


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 41


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 42


Data Structures Lab Dept. of CSE.

Outcomes:
Student will be able to use the knowledge gained through generic implementation of Linked list
and apply it to Stack and Queue operations.

DISCUSSION TOPICS
1. What is the principle of stack?

2. What is the principle of queue?

3. Explain the difference between stack using array and linked list?

4. List a few applications of Queue in programming?

Geethanjali College of Engineering and Technology Page 43


Data Structures Lab Dept. of CSE.

5. List a few applications of Stack in programming?

WEEK 5 : Date:
Write a C program to implement the following:
a) Towers of Hanoi.
b) Parenthesis Checker (by using stack ).

Objectives:
Student will learn about practical implementation of Stack ADT.
A. Algorithm/Pseudocode: Towers of Hanoi
Start
Procedure Hanoi(n, disk, source, aux)
If disk=1 then
Move disk from source to dest
Else
Hanoi(disk-1,source,aux,dest)
Move disk from source to dest

Geethanjali College of Engineering and Technology Page 44


Data Structures Lab Dept. of CSE.

Hanoi(disk-1,aux,dest,source)
END IF
Program:

Geethanjali College of Engineering and Technology Page 45


Data Structures Lab Dept. of CSE.

Input Output

B. Algorithm/Pseudocode: Parenthesis Checker


Step 1: Start
Step 2: Declare a character stack S
Step 3:Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else parenthesis are not balanced.
Step 4: After complete traversal, if there is some starting bracket left in stack then “not balanced”
Step 5: End of the Algorithm
Program:

Geethanjali College of Engineering and Technology Page 46


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 47


Data Structures Lab Dept. of CSE.

Input Output

Outcomes:
Student gains the knowledge to solve and implement an application using stack ADT.
DISCUSSION TOPICS
1. What is polish notation?

Geethanjali College of Engineering and Technology Page 48


Data Structures Lab Dept. of CSE.

2. Define reverse polish notation?

3. Parenthesis is never required in Postfix or Prefix expressions, why?

WEEK 6: Write a C program to implement Circular Queue using array and linked list.

Objectives:
Student will learn about practical implementation of Queue ADT.

Algorithm/Pseudocode: Circular Queue


Front: Get the front item from queue.
Rear: Get the last item from queue.
enQueue(value) This function is used to insert an element into the circular queue. In a circular
queue, the new element is always inserted at Rear position.
Steps:
1. Create a new node dynamically and insert value into it.
2. Check if front==NULL, if it is true then front = rear = (newly created node)
3. If it is false then rear=(newly created node) and rear node always contains the
address of the front node.
deQueue() This function is used to delete an element from the circular queue. In a queue, the
element is always deleted from front position.
Steps:
1. Check whether queue is empty or not means front == NULL.
2. If it is empty then display Queue is empty. If queue is not empty then step 3

Geethanjali College of Engineering and Technology Page 49


Data Structures Lab Dept. of CSE.

3. Check if (front==rear) if it is true then set front = rear = NULL else move the front
forward in queue, update address of front in rear node and return the element.
Program

Geethanjali College of Engineering and Technology Page 50


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 51


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 52


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 53


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the knowledge to understand the Circularly Queue Data structure.

DISCUSSION TOPICS
1. Explain the necessity of circular queue.

2. Differentiate between Queue and Circular Queue.

WEEK 7: Date:
Write C programs to implement a double ended queue ADT using linked list.

Objectives:
Student will learn to implement doubly linked list.
Algorithm/Pseudocode:
Algorithm for Insertion at rear end
1. Allocate space for a newnode of doubly linked list
2.if newnode == NULL then
print "Overflow"
3.else
if rear == NULL, then
rear = front = newnode
else
newnode->prev = rear
rear->next = newnode
rear = newnode

Algorithm for Insertion at front end


1. Allocate space for a newnode of doubly linked list

Geethanjali College of Engineering and Technology Page 54


Data Structures Lab Dept. of CSE.

2.if newnode == NULL then


print "Overflow"
3.else
if front == NULL, then
rear = front = newnode
else
newnode->next = front
front ->prev = newnode
front = newnode

Algorithm for Deletion at rear end


1. if front == NULL
print "Underflow"
2. else
Initialize temp = rear
rear = rear->prev
if rear == NULL
front = NULL
else
rear->next = NULL
3. Deallocate space for temp
Algorithm for Deletion at front end
if front == NULL
print "Underflow"
else
Initialize temp = front
front = front->next
if front == NULL
rear = NULL
else
front->prev = NULL
Deallocate space for temp

PROGRAM:

Geethanjali College of Engineering and Technology Page 55


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 56


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 57


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 58


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the knowledge of double ended queue ADT and can implement it using array or
linked list.

DISCUSSION TOPICS
1. Explain the necessity of double ended queue.

2. What is functionality of input restricted queue?

3. Explain functionality of output restricted queue.

WEEK 8:
a) Create a binary search tree of integers.
b) Traverse the above Binary search tree in in-order, pre-order, post-order.
Objectives:
Student will learn non-linear data structures with the implementation of Binary-Tree.

ALGORITHM/PSEUDOCODE: Create a Binary Tree


Step 1: Create an empty stack S.
Step 2: Initialize current node as root
Step 3: Push the current node to S and set current = current->left until current is NULL
Step 4: If current is NULL and stack is not empty then
Step 4.1: Pop the top item from stack.
Step 4.2: Print the popped item, set current = current->right
Step 4.3: Go to step 3.
Step 5: If current is NULL and stack is empty then we are done.
Step 6: Stop.

ALGORITHM/PSEUDOCODE: Perform traversal of Binary Tree


Step 1: Start
Step 2: Algorithm Inorder(tree)

Geethanjali College of Engineering and Technology Page 59


Data Structures Lab Dept. of CSE.

Step 2.1: Traverse the left subtree, i.e., call Inorder(left-subtree)


Step 2.2: Visit the root.
Step 2.3: Traverse the right subtree, i.e., call Inorder(right-subtree)
Step 3: Algorithm Preorder(tree)
Step 3.1: Visit the root.
Step3.2: Traverse the left subtree, i.e., call Preorder(left-subtree)
Step 3.3: Traverse the right subtree, i.e., call Preorder(right-subtree)
Step 4: Algorithm Postorder(tree)
Step 4.1: Traverse the left subtree, i.e., call Postorder(left-subtree)
Step 4.2: Traverse the right subtree, i.e., call Postorder(right-subtree)
Step 4.3: Visit the root.
Step 5: Stop.
PROGRAM:

Geethanjali College of Engineering and Technology Page 60


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 61


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 62


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 63


Data Structures Lab Dept. of CSE.

Outcomes:
Student will be able to create and perform various traversal algorithms on a Binary Tree.
DISCUSSION TOPICS
1. What is binary tree?

2. Differentiate between complete binary tree strictly binary tree?

3. What is the time complexity of binary tree?

WEEK 9:
Write C programs for implementing the following sorting methods to arrange a list of integers in
ascending order:
a) Merge sort b) Heap sort
Objectives:
Student will learn some of the algorithms to sort given data.
Merge sort
Algorithm/PSEUDOCODE:
Step 1: Start
Step 2: Create the variables and an array
Step 3: Print the elements enter by keyboard by for loop
Step 4: Call the function merge sort
Step 5: Initialize the variables
Step 6: if list size is 0(empty) or 1, consider it sorted and return it
Step 7: Using less than or equal prevents infinite recursion for a 0 length m
Step 8: if length(m) <= 1 then return m

Geethanjali College of Engineering and Technology Page 64


Data Structures Lab Dept. of CSE.

Step 9: Recursively call merge sort() to further split each sublist


Step 10: do until sublist size is 1
Step 11: Merge the sublists returned from prior calls to merge_sort()
Step 12: Return the resulting merged sublist
Step 13: Stop

PROGRAM:

Geethanjali College of Engineering and Technology Page 65


Data Structures Lab Dept. of CSE.

Input Output

b) Heap sort
ALGORITHM/PSEUDOCODE:

Step 1: Build a heap out of the data set.


Step 2: Remove the largest item and place it at the end of the sorted array.
Step 3: After removing the largest item, reconstruct the heap and remove the largest remaining
item and places it in the next open position from the end of the sorted array.
Step 4: Step (3) is repeated until there are no items left in the heap and the sorted array is full.

Geethanjali College of Engineering and Technology Page 66


Data Structures Lab Dept. of CSE.

Step 5: Implementations require two arrays - one to hold the heap and the other to hold the sorted
elements.

PROGRAM:

Geethanjali College of Engineering and Technology Page 67


Data Structures Lab Dept. of CSE.

Input output

Outcomes:
Student gains the knowledge to implement different sorting techniques on given list of elements.
a) Merge sort b)Heap sort

DISCUSSION TOPICS
1. What is the advantage of merge sort?

2. What is the advantage of Heap sort?

Geethanjali College of Engineering and Technology Page 68


Data Structures Lab Dept. of CSE.

3. Explain whether merge sort is stable or in-place?

WEEK 10 Date:
Write C programs for implementing the following sorting methods to arrange a list of integers in
ascending order:
a) Radix sort b) Binary Insertion sort
Objectives:
Student will learn some of the algorithms to sort given data.
Radix sort
Radix Sort is an algorithm that sorts a list of numbers and comes under the category of
distribution sort.
This sorting algorithm doesn't compare the numbers but distributes them, it works as follows:
ALGORITHM
Step 1: Sorting takes place by distributing the list of number into a bucket by passing through the
individual digits of a given number one-by-one beginning with the least significant part. Here,
the number of buckets are a total of ten, which bare key values starting from 0 to 9.
Step 2: After each pass, the numbers are collected from the buckets, keeping the numbers in
order
Step 3: Now, recursively redistribute the numbers as in the above Step '1' but with a following
reconsideration: take into account next most significant part of the number, which is then
followed by above Step '2'.
PROGRAM:

Geethanjali College of Engineering and Technology Page 69


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 70


Data Structures Lab Dept. of CSE.

b) Binary insertion sort


Binary insertion sort is a sorting algorithm similar to insertion sort, but instead of using linear
search to find the position where the element should be inserted, we use binary search. Thus, we
reduce the number of comparisons for inserting one element from O(N) to O(log N).

ALGORITHM
Step 1: Iterate the array from the second element to the last element.

Step 2: Store the current element A[i] in a variable key.

Step 3: Find the position of the element just greater than A[i] in the subarray from A[0] to A[i-
1] using binary search. Say this element is at index pos.

Step 4: Shift all the elements from index pos to i-1 towards the right.

Step 5: A[pos] = key.

Program

Geethanjali College of Engineering and Technology Page 71


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 72


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 73


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the knowledge to implement different sorting techniques on given list of elements.
a) Radix sort b) Binary insertion sort

DISCUSSION TOPICS
1. Show the importance of Radix sort?

2. What is the advantage of Binary insertion sort ?

3. What is the time complexity of Radix sort ?

WEEK 11 Date:
Write a C program to perform the following operation:
a) Insertion into a B-tree. b) Searching a B-Tree.
Algorithm/Pseudocode:

Step 1: Start
Step 2: Create a structure
Step 3: Create a new node
Step 4: Places the value in appropriate position
Step 5: Split the node

Geethanjali College of Engineering and Technology Page 74


Data Structures Lab Dept. of CSE.

Step 6: Sets the value val in the node


Insertion
Step 1: Start
Step 2: Find the node in the tree
Step 3: Place the node in the proper position
Step 4: Adjust the node
Step 5: Stop
Deletion
Step 1: Start
Step 2: Find the node in the tree
Step 3: If node is not found then print error
Step 4: If node is leaf then remove it and adjust the node
Step 5: Stop
PROGRAM:

Geethanjali College of Engineering and Technology Page 75


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 76


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 77


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 78


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 79


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 80


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the knowledge to implement operations on a B Tree
DISCUSSION TOPICS
1. List the efficient search trees available in Data Structures?

2. State the advantage of B-tree?

3. What is time complexity of B-tree?

WEEK 12 Date:
Write C programs for implementing the following graph traversal algorithms:
a) Depth first traversal. b) Breadth first traversal.
Objectives:
Student will learn about graph traversal algorithms.
Algorithm for DFS
1. Start at some node ‘i’. This is now our current node.
2. State that our current node is ‘visited’.
3. Now look at all nodes adjacent to our current node.
4. If we see an adjacent node that has not been ‘visited’, add it to the stack.
5. Then pop of the top node on the stack and traverse to it.
6. And go back to step 1.
This algorithm terminates when all nodes have been visited, the stack is empty.
Program:

Geethanjali College of Engineering and Technology Page 81


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 82


Data Structures Lab Dept. of CSE.

Input Output

Algorithm for BFS


1. Start at some node ‘i’. This is now our current node.
2. State that our current node is ‘visited’.
3. Now look at all nodes adjacent to our current node.

Geethanjali College of Engineering and Technology Page 83


Data Structures Lab Dept. of CSE.

4. If we see an adjacent node that has not been ‘visited’, add it to the queue.
5. Then pull out the first node on from the queue and traverse to it.
6. And go back to step 1.
Program:

Geethanjali College of Engineering and Technology Page 84


Data Structures Lab Dept. of CSE.

Input Output

Outcomes:
Student gains the knowledge to implement graph traversal algorithms.

DISCUSSION TOPICS
1. Define graph with respect to Data structures in C?

2. What is weighted and directed graph?

Geethanjali College of Engineering and Technology Page 85


Data Structures Lab Dept. of CSE.

3. What is the advantage of DFS & BFS?

WEEK 13 Date:
Write a C program to implement all the functions of a dictionary (ADT) using hashing.
Objectives:
Student will learn about concept of Hashing.
ALGORITHM:
Step1:Start
Step2:initialize the variables
Step3:create structure
Step4:Enter number of elements
Step5:read ch value if
Case1-insertion
Case2-deletion
Case3- searching
Case4- display
Case5-exit
Step6: :Select case 1 for insertion perform
void insertInHash(int key, char *name, int age) {
int hashIndex = key % tableSize;
if (tableSize == totEle) {
printf("Can't perform Insertion..Hash Table is full!!");
return;
}
while (hashTable[hashIndex].marker == 1) {
hashIndex = (hashIndex + 1)%tableSize;
}
hashTable[hashIndex].key = key;
hashTable[hashIndex].age = age;
strcpy(hashTable[hashIndex].name, name);
hashTable[hashIndex].marker = 1;
totEle++;
return;
}
Step7:Select case2 for deletion as

Geethanjali College of Engineering and Technology Page 86


Data Structures Lab Dept. of CSE.

void deleteFromHash(int key) {


int hashIndex = key % tableSize, count = 0, flag = 0;
if (totEle == 0) {
printf("Hash Table is Empty!!\n");
return;
}
Step8:Select case 3 for searching
void searchElement(int key) {
int hashIndex = key % tableSize, flag = 0, count = 0;
if (totEle == 0) {
printf("Hash Table is Empty!!");
return;
}
Step9:Select case4 for display
void display() {
int i;
if (totEle == 0) {
printf("Hash Table is Empty!!\n");
return;
}
printf("Voter ID Name Age Index \n");
Step10:Select case 5 to exit.
Step11:End

Program:

Geethanjali College of Engineering and Technology Page 87


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 88


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 89


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 90


Data Structures Lab Dept. of CSE.

Input Output

Outcomes:
Student gains the knowledge to implement all the functions of a dictionary (ADT) using hashing.

DISCUSSION TOPICS
1. Explain hashing?

2. Explain various types of hash functions?

3. Explain types of hashing?

4. What are the advantages of hashing?

WEEK 14 Date:
Write a C program for pattern matching using Knuth-Morris-Pratt algorithm.
Objectives:
Student will learn about pattern matching algorithm (KMP).
ALGORITHM:

Geethanjali College of Engineering and Technology Page 91


Data Structures Lab Dept. of CSE.

Algorithm to find overlap in the given pattern:


Input : pattern in which overlap needs to be found
Output: Overlap array
i<-2, j<-0, len<-strlen(pattern)
overlap[0] <- -1, overlap[1] <- 0
while i < len
if pattern[i - 1] equal to pattern[j]
j <- j + 1, ptr[i++] <- j;
otherwise if j greater than 0
j <- ptr[j]
otherwise
ptr[i++] <- 0
end while

Algorithm for Knuth-Morris-Pratt(KMP) Searching:


Input : Target string, Pattern and Overlap array
Output : Index of the Pattern in Target string
i->0, j->0, count->0
while i + j is lesser than strlen(Target)
if pattern[j] equals Target[i + j],
if j equals strlen(word) - 1)
return index of pattern
j <- j + 1;
otherwise,
i <- i + j - overlap[j];
if overlap[j] is greater than -1)
j <- overlap[j]
otherwise,
j <- 0;
end while
Target : abc abcdabcdabd
Pattern: abcdabd

PROGRAM:

Geethanjali College of Engineering and Technology Page 92


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 93


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 94


Data Structures Lab Dept. of CSE.

Outcomes:
Student gains the knowledge to implement pattern matching algorithm (KMP).
DISCUSSION TOPICS
1. What is pattern matching?

2. Explain the importance of KMP algorithm?

3. List some of the pattern matching algorithms?

ADDITIONAL PROGRAMS

1. Write a C program to implement stack operation using array.

Geethanjali College of Engineering and Technology Page 95


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 96


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 97


Data Structures Lab Dept. of CSE.

2. Write a C program to display elements of Doubly linked list in reverse order.

Geethanjali College of Engineering and Technology Page 98


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 99


Data Structures Lab Dept. of CSE.

Input Output

3. Write a C program to merge of the contents of a two Singly linked list and display in sorted
order.

Geethanjali College of Engineering and Technology Page 100


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 101


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 102


Data Structures Lab Dept. of CSE.

1.Write a C program to implement following operations on Binary search tree:


(i) Insertion.
(ii) Deletion
a) Node with no child (leaf node).
b) Node with one child.
c) Node with two children.

Geethanjali College of Engineering and Technology Page 103


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 104


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 105


Data Structures Lab Dept. of CSE.

Geethanjali College of Engineering and Technology Page 106


Data Structures Lab Dept. of CSE.

Input Output

Geethanjali College of Engineering and Technology Page 107

You might also like