Vtu DSA Lab Manual Related Can Help You

Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

Best VTU Student Companion App You Can Get

DOWNLOAD NOW AND GET


Instant VTU Updates, Notes, Question Papers,
Previous Sem Results (CBCS), Class Rank, University Rank,
Time Table, Students Community, Chat Room and Many
More

CLICK BELOW TO DOWNLOAD VTU CONNECT APP


IF YOU DON’T HAVE IT

* Visit https://vtuconnect.in for more info. For any queries or questions wrt our
platform contact us at: [email protected]
VTU Connect Android App Download Now On Google Play Store

ATME COLLEGE OF ENGINEERING


13th KM Stone, Bannur Road, Mysore - 560 028

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


(ACADEMIC YEAR 2020-21)

LABORATORY MANUAL

SUBJECT: DATA STRUCTURES LABORATORY

SUB CODE: 18CSL38


SEMESTER: III-2018 CBCS Scheme

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

INSTITUTIONAL MISSION AND VISION

Objectives
 To provide quality education and groom top-notch professionals, entrepreneurs and
leaders for different fields of engineering, technology and management.
 To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research in
areas of social relevance, and develop the institute as a center of excellence.
 To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
 To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
 To cultivate strong community relationships and involve the students and the staff in
local community service.
 To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.

Vision
 Development of academically excellent, culturally vibrant, socially responsible and
globally competent human resources.

Mission
 To keep pace with advancements in knowledge and make the students competitive and
capable at the global level.
 To create an environment for the students to acquire the right physical, intellectual,
emotional and moral foundations and shine as torch bearers of tomorrow’s society.
 To strive to attain ever-higher benchmarks of educational excellence.

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

Department of Computer Science & Engineering

Vision of the Department

 To develop highly talented individuals in Computer Science and Engineering to deal with
real world challenges in industry, education, research and society.

Mission of the Department

 To inculcate professional behavior, strong ethical values, innovative research capabilities


and leadership abilities in the young minds & to provide a teaching environment that
emphasizes depth, originality and critical thinking.

 Motivate students to put their thoughts and ideas adoptable by industry or to pursue
higher studies leading to research.

Program Outcomes (POs)

Engineering Graduates will be able to:

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2. 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.

PO3. 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.

PO4. 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.

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

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

PO6. 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.

PO7. 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.

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

PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

PO10. 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.

PO11. 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.

PO12. 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.

Program Specific Outcomes (PSOs)

1. Demonstrate understanding of the principles and working of the hardware and


software aspects of Embedded Systems.
2. Use professional Engineering practices, strategies and tactics for the development,
implementation and maintenance of software.
3. Provide effective and efficient real time solutions using acquired knowledge in various
domains.

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

Program Educational Objectives (PEOs):

1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment,
higher learning and R&D.

2. Gain technical knowledge, skills and awareness of current technologies of computer


science engineering and to develop an ability to design and provide novel engineering
solutions for software/hardware problems through entrepreneurial skills.

3. Exposure to emerging technologies and work in teams on interdisciplinary projects


with effective communication skills and leadership qualities.

4. Ability to function ethically and responsibly in a rapidly changing environment by


applying innovative ideas in the latest technology, to become effective professionals in
Computer Science to bear a life-long career in related areas.

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

DATA STRUCTURES LABORATORY


(Effective from the academic year 2018 -2019)
SEMESTER – III
Subject Code 18CSL38 CIE Marks 40
Number of Contact Hours/Week 0:2:2 SEE Marks 60
Total Number of Lab Contact Hours 36 Exam Hours 3 Hrs.
Credits – 2
Course Learning Objectives: This course (18CSL38) will enable students to:
This laboratory courses enables students to get practical experience in design, develop, implement, analyze
and evaluation/testing of
 Asymptotic performance of algorithms.
 Linear data structures and their applications such as stacks, queues and lists
 Non-Linear data structures and their applications such as trees and graphs
 Sorting and searching algorithms
Descriptions (if any):
 Implement all the programs in ‘C / C++’ Programming Language and Linux / Windows as OS.
Programs List:
1. Design, Develop and Implement a menu driven Program in C for the following array
operations.
a. Creating an array of N Integer Elements
b. Display of array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position (POS)
e. Exit.
Support the program with functions for each of the above operations.
2. Design, Develop and Implement a Program in C for the following operations on Strings.
a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR
with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in
STR
Support the program with functions for each of the above operations. Don't use Built-in
functions.
3. Design, Develop and Implement a menu driven Program in C for the following operations on
STACK of Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations

4. Design, Develop and Implement a Program in C for converting an Infix Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized
expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric
operands.

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

5. Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %,
^
b. Solving Tower of Hanoi problem with n disks

6. Design, Develop and Implement a menu driven Program in C for the following operations on
Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations

7. Design, Develop and Implement a menu driven Program in C for the following operations on
Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL (Demonstration of stack)
e. Exit

8. Design, Develop and Implement a menu driven Program in C for the following operations on
Doubly Linked List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation,
Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit

9. Design, Develop and Implement a Program in C for the following operations on


Singly Circular Linked List (SCLL) with header nodes
a. Represent and Evaluate a Polynomial P (x, y, z) = 6x2y2z-4yz5+3x3yz+2xy5z-2xyz3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the
result in POLYSUM(x,y,z)
Support the program with appropriate functions for each of the above operations

10. Design, Develop and Implement a menu driven Program in C for the following operations on
Binary Search Tree (BST) of Integers.
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in IN order, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
11. Design, Develop and Implement a Program in C for the following operations on Graph(G)
of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine
the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m
memory locations with L as the set of memory addresses (2-digit) of locations in HT. Let the
keys in K and addresses in L are Integers. Design and develop a Program in C that uses Hash
function H: K L as H(K)=K mod m (remainder method), and implement hashing technique
to map a given key K to the address space L. Resolve the collision (if any) using
linear probing.
Laboratory Outcomes: The student should be able to:
 Analyze and Compare various linear and non-linear data structures
 Code, debug and demonstrate the working nature of different types of data structures and their
applications
 Implement, analyze and evaluate the searching and sorting algorithms
 Choose the appropriate data structure for solving real world problems
Conduct of Practical Examination:
 Experiment distribution
o For laboratories having only one part: Students are allowed to pick one experiment from the
lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal opportunity.
 Change of experiment is allowed only once and marks allotted for procedure to be made zero of the
changed part only.
 Marks Distribution (Courseed to change in accoradance with university regulations)
c) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 =
100 Marks
d) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store

CONTENTS

Sl.No. EXPERIMENT NAME Page No


1. Introduction 1
2. Program 1 : Array Operations 6
3. Program 2 : String Operations 14
4. Program 3 : Stack Operations 19
5. Program 4 : Infix to Postfix Conversion 29
6. Program 5: Design, Develop and Implement Program in C
for the following Stack Applications
a. Evaluation of Suffix expression with single 34
digit operands and operators: +, -, *, /,%, ^.
b. Solving Tower of Hanoi problem withndisks 37
7. Program 6 : Circular Queue Operations 40
8. Program 7 : Implementation of Singly Linked List 46
9. Program 8 : Implementation of Doubly Linked List 60
10. Program 9 : Polynomial Evaluation & Addition using
SCLL with header node 75

11. Program 10 : Implementation of Binary Search tree 83


12. Program 11 : Implementation of Graphs (BFS & DFS
Methods) 92

13. Program 12 : Implementation of Hashing & Linear Probing 101

VTU Connect Android App Download Now On Google Play Store


VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Introduction to Data Structure


Basic Concepts
The logical or mathematical model of a particular organization of data is called data
structures. Data structures is the study of logical relationship existing between individual data
elements, the way the data is organized in the memory and the efficient way of storing,
accessing and manipulating the data elements.

Data Structures can be classified as:


 Primitive data structures
 Non-Primitive data structures.

Primitive data structures are the basic data structures that can be directly
manipulated/operated by machine instructions. Some of these are character, integer, real,
pointers etc.

Non-primitive data structures are derived from primitive data structures, they cannot be
directly manipulated/operated by machine instructions, and these are group of homogeneous or
heterogeneous data items. Some of these are Arrays, stacks, queues, trees, graphs etc.

Data structures are also classified as


 Linear data structures
 Non-Linear data structures.

In the Linear data structures processing of data items is possible in linear fashion, i.e., data can
be processed one by one sequentially.
Example of such data structures are:
 Array
 Linked list
 Stacks
 Queues

A data structure in which insertion and deletion is not possible in a linear fashion is
called as non linear data structure. i.e., which does not show the relationship of logical
adjacency between the elements is called as non-linear data structure. Such as trees, graphs and
files.

Data structure operations:


The particular data structures that one chooses for a given situation depends largely on
the frequency with which specific operations are performed.

DEPT OF CSE, ATMECE, MYSURU Page 1


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

The following operations play major role in the processing of data.


i) Traversing.
ii) Searching.
iii) Inserting.
iv) Deleting.
v) Sorting.
vi) Merging

STACKS:
A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at the same end, called the TOP of the stack. A stack is a
non-primitive linear data structure.1 2 3 4 5

As all the insertion and deletion are done from the same end, the first element inserted
into the stack is the last element deleted from the stack and the last element inserted into the
stack is the first element to be deleted. Therefore, the stack is called Last-In First-Out (LIFO)
data structure.

QUEUES:
A queue is a non-primitive linear data structure. Where the operation on the queue is
based on First-In-First-Out FIFO process — the first element in the queue will be the first one
out. This is equivalent to the requirement that whenever an element is added, all elements that
were added before have to be removed before the new element can be removed.

For inserting elements into the queue are done from the rear end and deletion is done
from the front end, we use external pointers called as rear and front to keep track of the status
of the queue. During insertion, Queue Overflow condition has to be checked. Likewise during
deletion, Queue Underflow condition is checked.

APPLICATION OF QUEUE
Queue, as the name suggests is used whenever we need to have any group of objects in an
order in which the first one coming in, also gets out first while the others wait for their turn,
like in the following scenarios :
 Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
 In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
 Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive, First come first served.

DEPT OF CSE, ATMECE, MYSURU Page 2


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

LINKED LIST
Disadvantages of static/sequential allocation technique:
 If an item has to be deleted then all the following items will have to be moved by one
allocation. Wastage of time.
 Inefficient memory utilization.
 If no consecutive memory (free) is available, execution is not possible.

Linear Linked Lists


Types of Linked lists:
 Single Linked lists
 Circular Single Linked Lists
 Double Linked Lists
 Circular Double Linked Lists.

NODE:
Each node consists of two fields. Information (info) field and next address (next) field. The
info field consists of actual information/data/item that has to be stored in a list. The second
field next/link contains the address of the next node. Since next field contains the address,

It is of type pointer. Here the nodes in the list are logically adjacent to each other. Nodes that
are physically adjacent need not be logically adjacent in the list.

The entire linked list is accessed from an external pointer FIRST that points to (contains the
address of) the first node in the list. (By an “external” pointer, we mean, one that is not
included within a node. Rather its value can be accessed directly by referencing a variable).

Fig-1 Linked List

The list containing 4 items/data 10, 20, 30 and 40 is shown below.

Fig-2 Linked List


The nodes in the list can be accessed using a pointer variable. In the above fig. FIRST is the
pointer having the address of the first node of the list, initially before creating the list, as list is
empty. The FIRST will always be initialized to NULL in the beginning. Once the list is
created, FIRST contains the address of the first node of the list.

DEPT OF CSE, ATMECE, MYSURU Page 3


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

As each node is having only one link/next, the list is called single linked list and all the
nodes are linked in one direction. Each node can be accessed by the pointer pointing (holding
the address) to that node, Say P is pointer to a particular node, then the information field of that
node can be accessed using info(P) and the next field can be accessed using next(P).

The arrows coming out of the next field in the fig. indicates that the address of the
succeeding node is stored in that field. The link field of last node contains a special value
known as NULL which is shown using a diagonal line pictorially. This NULL pointer is used
to signal the end of a list.

The basic operations of linked lists are Insertion, Deletion and Display. A list is a
dynamic data structure. The number of nodes on a list may vary dramatically as elements are
inserted and deleted(removed).

The dynamic nature of list may be contrasted with the static nature of an array, whose
size remains constant. When an item has to inserted, we will have to create a node, which has
to be got from the available free memory of the computer system, So we shall use a mechanism
to find an unused node which makes it available to us. For this purpose we shall use the
getnode operation (getnode() function).

The C language provides the built-in functions like malloc(), calloc(), realloc() and
free(), which are stored in alloc.h or stdlib.h header files. To dynamically allocate and release
the memory locations from/to the computer system.

TREES:
Definition:
A data structure which is accessed beginning at the root node. Each node is either a
leaf or an internal node. An internal node has one or more child nodes and is called the parent
of its child nodes. All children of the same node are siblings. Contrary to a physical tree, the
root is usually depicted at the top of the structure, and the leaves are depicted at the bottom. A
tree can also be defined as a connected, acyclic di-graph.

Tree is a non-linear data structure which organizes data in hierarchical structure and this is a
recursive definition.
A tree data structure can also be defined as follows...
Tree data structure is a collection of data (Node) which is organized in hierarchical structure
and this is a recursive definition

Fig-3 Tree data structure

DEPT OF CSE, ATMECE, MYSURU Page 4


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Binary tree: A tree with utmost two children for each node.

Complete Binary Tree: A binary tree in which every level, except possibly the deepest, is
completely filled. At depth n, the height of the tree, all nodes must be as far left as possible.
Binary search tree: A binary tree where every node’s left subtree has keys less than the node's
key, and every right subtree has keys greater than the node's key.

Tree traversal is a technique for processing the nodes of a tree in some order.The
different tree traversal techniques are Pre-order, In-order and Post-order traversal.In Pre-order
traversal, the tree node is visited first and the left subtree is traversed recursively and later right
sub-tree is traversed recursively.

DEPT OF CSE, ATMECE, MYSURU Page 5


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 1
Design, Develop and Implement a menu driven Program in C for the
following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position (POS)
e. Exit.
Support the program with functions for each of the above operations

Program objective:
 Understand the working of array data structures.
 Understand the use of functions to implement each arrayoperation.
 Understand what is menu driven program and how to implement it.

Algorithm:
Step 1: Start.
Step 2: Read number of elements.(n)
Step 3: Read Array of N integerelements
Step 4: Display array contents and checking array empty condition
Step 5: Read valid position, to insert element into that position
Step 6: Delete an element at given valid position from an array.
Step 7: Stop

DEPT OF CSE, ATMECE, MYSURU Page 6


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY:

Array is a collection of elements of the same type. In this program we need to use functions for
various operations
Create (): Create an array for the size given by the user
Display (): Display the elements of the array
Insert (): Insert an element at the position given by the user
Delete (): Delete an element from the position specified by the user
Exit (): Terminate

Arrays are the kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows –
type array Name [ arraySize ];

This is called a single-dimensional array. The array Size must be an integer constant
greater than zero and type can be any valid C data type.

For example, to declare a 10-element array called balance of type double, use this statement –
double balance [10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.


Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows –
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array.
For example − double salary = balance [9];
The above statement will take the 10th element from the array and assign the value to
salary variable

DEPT OF CSE, ATMECE, MYSURU Page 7


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int a[20];
int n, val, i, pos, choice;
/*Function Prototype*/
void create();
void display();
void insert();
void delet();
int main()
{
while(1)
{
printf("\n\n--------MENU ---------- \n");
printf("1.CREATE\n");
printf("2.DISPLAY\n");
printf("3.INSERT\n");
printf("4.DELETE\n");
printf("5.EXIT\n");
printf(" ---------------------- ");
printf("\nENTER YOUR CHOICE:\t");
scanf("%d",&choice); //Reading userchoice
switch(choice)
{
case 1: create(); //to create anarray
break;
case 2:display(); //to display theelements
break;
case 3:insert(); // to insertelement
break;
case 4:
delet();//to delete an item at specific position

DEPT OF CSE, ATMECE, MYSURU Page 8


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

break;
case 5:exit(0); //exit the program
break;
default:printf("\nInvalidchoice:\n");
break;
}
}
}
//creating an array
void create()
{
printf("\nEnter the size of the array elements:\t");
scanf("%d",&n);
printf("\nEnter the elements for the array:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
}
//displaying an array elements
void display()
{
printf("\nThe array elements are:\n");

for(i=1;i<n;i++)
{
printf("%d\t",a[i]);
}
}

//inserting an element into an array


void insert()
{
printf("\nEnter the position for the new element:\t");
scanf("%d",&pos);
printf("\nEnter the element to be inserted :\t");

DEPT OF CSE, ATMECE, MYSURU Page 9


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

scanf("%d",&val);
for(i=n-1;i>=pos;i--)

a[i+1]=a[i];
a[pos]=val;
n++;
}
//deleting an array element
void delet()
{
printf("\nEnter the position of the element to be deleted:\t");
scanf("%d",&pos);
val=a[pos];
for(i=pos;i<n;i++)
{
a[i]=a[i+1];
}

printf("\nThe deleted element is =%d",val);


n--;
}

DEPT OF CSE, ATMECE, MYSURU Page 10


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output

----- MENU ---


1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOURCHOICE:
1
Enter the size of the arrayelements:
4
Enter the elements for the array:
10 20 30 40
----- MENU ---
1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOUR CHOICE:
2
The array elementsare:
10 20 30 40
----- MENU ---
1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOUR CHOICE:
3

DEPT OF CSE, ATMECE, MYSURU Page 11


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter the position for the new element:


0

Enter the element to be inserted:


50
----- MENU ---
1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOUR CHOICE:
2
The array elements are:
50 10 20 30 40
----- MENU ---
1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOUR CHOICE:
4
Enter the position of the element to be deleted:
0
The deleted element is =50

----- MENU ---


1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------

DEPT OF CSE, ATMECE, MYSURU Page 12


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

ENTER YOUR CHOICE:


2
The array elementsare:
10 20 30 40

----- MENU ---


1. CREATE
2. DISPLAY
3. INSERT
4. DELETE
5. EXIT
-----------
ENTER YOUR CHOICE:
5

Program outcome:
 Implement the menu driven C program using switch statement.
 Implement an array of any size and all the possible operations onarray.
 Identify the different applications where arrays can be used.
 Familiarized with the usage of functions in program.

Viva Questions:
 What is a array?
 What is two dimensional array?
 How to access elements of array?
 Can you change size of array once created?\
 What is two dimensional array?
 How An array elements are always stored in memory locations.?

DEPT OF CSE, ATMECE, MYSURU Page 13


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 2
Design, develop and implement a Program in C for the following operations
on Strings
a. Read a main String (STR), a Pattern String (PAT) and a Replace String
(REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences
of PAT in STR with REP if PAT exists in STR. Report suitable messages
in case PAT does not exist in STR
Support the program with functions for each of the above operations. Don't
use Built-in functions

Program objective:
 Understand the implementation of string function’s using arrays.
 Understand pattern matching algorithm and the implementationtechniqueof
the same without using built-in functions.
 Understand the pattern replacement methodology.

Algorithm:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: compare pattern string in main string,
Step 4: if PAT is found then replace all occurrences of PAT in main string STR
with REP string.
Step 5: if PAT is not found give a suitable error message.
Step 6: Stop.

DEPT OF CSE, ATMECE, MYSURU Page 14


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by a
null.

The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
C language supports a wide range of built-in functions that manipulate null-terminated strings
as follows:

strcpy(s1, s2); Copies string s2 into string s1.


strcat(s1, s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

DEPT OF CSE, ATMECE, MYSURU Page 15


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
char STR[100],PAT[100],REP[100],ans[100];
int c,i,j,k,m,flag=0;
void read()
{
printf("\nEnter the MAIN string: \n");
gets(STR);
printf("\nEnter a PATTERN string: \n");
gets(PAT);
printf("\nEnter a REPLACE string: \n");
gets(REP);
}
Void match()
{
m=c=i=j=k=0;
while ( STR[c] != '\0') //Check till the end of the main string
{
// Checking for Match
if ( STR[m] == PAT[i] ) //Cmp main with pattern
{
i++;
m++;
if ( PAT[i] == '\0')
{
//copy replace string in ans string
flag=1;
While(REP[j]!=’/0’)
{
ans[k++]=REP[j++];
}

c=m;
i=0;
}
} else //mismatch

DEPT OF CSE, ATMECE, Mysuru Page 16


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

ans[k++] = STR[c++]; //copy non-matched char t

m = c;
i=0;
}

}
if(flag==0)
{
printf("Pattern doesn't found!!!");
}
else
{
ans[k] = '\0';
printf("\nThe RESULTANT string is:%s\n" ,ans);
}
}
Void main()
{
read();
match();
}

Output 1
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
engg
Enter a REPLACE string:
engineering
The RESULTANT string is: atme college of engineering
Output 2
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
for
Enter a REPLACE string:
if
Pattern doesn't found!!!
DEPT OF CSE, ATMECE, MYSURU Page 17
VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output 3
Enter the MAIN string:
This is Data Structure lab
Enter a PATTERN string:
Data Structure
Enter a REPLACE string:
Data structure with C
The RESULTANT string is: This is Data structure with C lab

Program outcomes:
 Implement string matching and string replacement algorithm without using
built-in library functions.
 Apply the knowledge of array usage to implement string functions.
 Identify different applications of string matching and stringreplacement.

Viva Questions:
 What is a string?
 How strings are represented in C language? What does strlen do in C?
 Is there a string data type in C? What is the use of char in C programming?

DEPT OF CSE, ATMECE, MYSURU Page 18


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 3
Design, Develop and Implement a menu driven Program in C for the
following operations on STACK of Integers (Array Implementation of Stack
with maximum size MAX)
a. Push an Element on toStack
b Pop an Element from Stack
c Demonstrate how Stack can be used to check Palindrome
d Demonstrate Overflow and Underflow situations on Stack
e Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the
above operations.

Program objective:
 Understand the concept of palindrome.
 Understand the stack data structures.
 Understand the different functions on stacks i.e., push, pop and implement the
same.
 Understand stack overflow and underflow.

Algorithm:
PUSH (item)
Step 1: Read an element to be pushed on to stack item
Step 2: check overflow condition of stack before inserting element into
stack Top=max-1
Step 3: update the top pointer and insert an element into stack
Top=top+1
S[top] <-item

POP (item)
Step1: check underflow condition of stack before deleting element from stack
top=-1
Step2: Display deleted element pointed by top
Deleted element<- s[top]
Step3: Decrement top pointer by 1
top<-top-1

DEPT OF CSE, ATMECE, MYSURU Page 19


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Palindrome
Step 1: Two pointers are required , one is pointed to top of stack
another is bottom of stack
Step 2: compare top and bottom elements of stack if it is equal update top and
bottom pointer by1
Step 3: if all elements are equal, then stack content is palindrome

DEPT OF CSE, ATMECE, MYSURU Page 20


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
It is called as last in, first out. The element inserted first is the last one to be deleted. It
is used for various applications like infix to postfix expression, postfix evaluation and for
maintaining stack frames for function calling

A real-world stack allows operations at one end only. For example, we can place or
remove a card or plate from top of the stack only. Likewise, Stack ADT allows all data
operations at one end only.

At any given time, we can only access the top element of a stack. This feature makes it
LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed
(inserted or added) last is accessed first. In stack terminology, insertion operation is called
PUSH operation and removal operation is called POP operation.

Below given diagram tries to depict a stack and its operations −

Fig4-Example of Stack

A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack
can either be a fixed size one or it may have a sense of dynamic resizing.

Here, we are going to implement stack using arrays which makes it a fixed size stack
implementation.

Basic Operations performed on stack:


 push() - pushing (storing) an element on the stack.
 pop() - removing (accessing) an element from the stack.
To use a stack efficiently we need to check status of stack as well. For the same
purpose, the following functionality is added to stacks;
 peek() − get the top data element of the stack, without removing it.
 isFull() − check if stack is full.
 isEmpty() − check if stack is empty.

DEPT OF CSE, ATMECE, MYSURU Page 21


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdlib.h>
#include<stdio.h>
#define max_size 5
int stack[max_size],top=-1;
/*Function Prototype*/
void push();
void pop();
void display();
void pali();
int main()
{
int
choice;
while(1)
{
printf("\n\n--------STACK OPERATIONS ----------- \n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Palindrome\n");
printf("4.Display\n");
printf("5.Exit\n");
printf(" ---------------------- ");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: push(); //to insert an item intostack
break;
case 2: pop();//to delete an item fromstack
break;
case 3: pali();//to check palindrome or not
break;
case 4: display(); //to display items instack
break;
case 5: exit(0); //exit the program
break;
default: printf("\n Invalidchoice:\n");

DEPT OF CSE, ATMECE, MYSURU Page 22


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

break;

}
}
return 0;
}
void push() //Inserting element into the stack
{
int item;
if (top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThepoped element: %d\t",item);
}
}

DEPT OF CSE, ATMECE, MYSURU Page 23


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void pali() //checking whether palindrome or not


{
int num[10],rev[10],i=0,k,flag=1;
k=top;
while(k!=-1)
{
num[i++]=stack[k--];
}
for(i=0;i<=top;i++)
{

if(num[i]==stack[i])
continue;
else
flag=0;
}
if(top!=-1)
{
if(flag)
printf("It is palindrome number\n");
else
printf("It is not a palindrome number\n");
}
else
printf("Stack is Empty:");
}

void display() //Displaying the elements of stack


{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}

DEPT OF CSE, ATMECE, MYSURU Page 24


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}

Output

------- STACK OPERATIONS ------


1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 1
enter element to be inserted
10
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 1
enter element to be inserted
20
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit

DEPT OF CSE, ATMECE, MYSURU Page 25


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter your choice 1


enter element to be inserted
30
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 1
enter element to be inserted
40
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 1
enter element to be inserted
50
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 1
Stack Overflow:
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 4

DEPT OF CSE, ATMECE, MYSURU Page 26


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

stack elements are:


50 40 30 20 10

------- STACK OPERATIONS------


1.Push
2.Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 2
The poped element: 50
------- STACK OPERATIONS------
1.Push
2.Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 2
The poped element: 40
------- STACK OPERATIONS------
1.Push
2.Pop
3. Palindrome
4. Display
5. Exit
Enter the choice
2
The poped element: 30
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter your choice 2
The poped element: 20

DEPT OF CSE, ATMECE, MYSURU Page 27


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

------- STACK OPERATIONS------


1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
Enter the choice
2
The poped element: 10
------- STACK OPERATIONS------
1. Push
2. Pop
3. Palindrome
4. Display
5. Exit
The enter the choice 2
Stack is Empty
Program outcome :
 Analyze the stack overflow and underflow conditions.
 Identify different application of stacks.
 Implement to check palindrome numbers using stacks.
 Familiarized with push and pop operations on stack.

Viva Questions:
 What is Stack and where it can be used?
 What is the difference between PUSH and POP?
 Differentiate STACK from ARRAY.
 What is the difference between a stack and a Queue?

DEPT OF CSE, ATMECE, MYSURU Page 28


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 4
Design, develop and implement a Program in C for converting an Infix
Expression to Postfix Expression. Program should support for both
parenthesized and free parenthesized expressions with the operators: +, -, *,
/, %( Remainder), ^ (Power) and alphanumeric operands.

Program objective:
 Understand different notations to represent regular expression.
 Understand infix to postfix conversion.
 Understand the precedence of operators.

Algorithm:
Step 1: Read the infix expression as a string.
Step 2: Scan the expression character by character till the end. Repeat the
following operations
1. If it is an operand add it to the postfix expression.
2. If it is a left parenthesis push it onto the stack.
3. If it is a right parentheses pop out elements from the stack and assign it to
the postfix string. Pop out the left parentheses but don’t assign to postfix.

Step 3: If it is an operator compare its precedence with that of the element at the
top of stack.
1. If it is greater push it onto the stack.
2. Else pop and assign elements in the stack to the postfix expression until
you find one such element.
Step 4: If you have reached the end of the expression, pop out any leftover
elements in the stack till it becomes empty.
Step 5: Append a null terminator at the end display the result

DEPT OF CSE, ATMECE, MYSURU Page 29


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
Infix: Operators are written in-between their operands. Ex: X + Y
Prefix: Operators are written before their operands. Ex: +X Y postfix: Operators are written
after their operands. Ex: XY+

Examples of Infix, Prefix, and Postfix

Infix Expression Prefix Expression Postfix Expression

A+B +AB AB+

A+B*C +A*BC ABC*+

Infix to prefix conversion Expression = (A+B^C)*D+E^5

Step 1. Reverse the infix expression.


5^E+D*)C^B+A(

Step 2. Make Every '(' as ')' and every ')' as '('


5^E+D*(C^B+A)

Step 3. Convert expression to postfix form.

Step 4. Reverse the expression.


+*+A^BCD^E

Step 5. Result
+*+A^BCD^E5

DEPT OF CSE, ATMECE, MYSURU Page 30


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include <ctype.h>
#include <stdio.h>
#define SIZE 50 /* Size of Stack */
char s[SIZE]; /* Global declarations */
int top = -1;
push(char elem) /* Function for PUSH operation */
{
s[++top] = elem;
}
char pop() /* Function for POP operation */
{
return (s[top--]);
}
int pr(char elem) /* Function for precedence */
{
switch (elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/':
case '%': return 3;
case '^': return 4;
}
}

DEPT OF CSE, ATMECE, MYSURU Page 31


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void main() /* Main Program */


{
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("\n\n enter the Infix Expression : ");
gets(infx);
push('#');
while ((ch = infx[i++]) != '\0')
{
if (ch == '(')
push(ch);
else if(isalnum(ch))
pofx[k++] = ch;
else if (ch == ')')
{
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
}
else /* Operator */
{
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\n Given Infix Expn is: %s\n The Postfix Expn is:
%s\n", infx, pofx);
}

DEPT OF CSE, ATMECE, MYSURU Page 32


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output1
enter the Infix Expression
((a+b)*c)
Given Infix Expn is: ((a+b)*c)
The Postfix Expn is: ab+c*

Output 2
enter the Infix Expression
(a+ (b-c)*d)
Given Infix Expn is: (a+ (b-c)*d)
The Postfix Expn is: abc-d*+

Program outcome :
 Identify the applications of infix and postfix.
 Implement C program to convert infix to postfix.
 Identify the different operators.

Viva Questions:
 What is a postfix expression?
 What are Infix, prefix, Postfix notations?
 What is the evaluation order according to which an infix expressionis
converted to postfix expression ?
 which data structure is used for infix to postfix conversion

DEPT OF CSE, ATMECE, MYSURU Page 33


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 5
Design, develop and implement a Program in C forthe following Stack
Applications
a. Evaluation of Suffix expression with single digit operands and
operators: +, -, *, /,%, ^
b. Solving Tower of Hanoi problem with n disks

Program objective :
 Understand different polish notation.
 Understand the methodology of evaluating suffix expression.
 Get the knowledge of operator precedence and associativity.

Algorithm
Step 1: Read the suffix/postfix expression
Step 2: Scan the postfix expression from left to right character by character
Step 3: if scanned symbol is operand push data into stack.
If scanned symbol is operator pop two elements from stack Evaluate result
and result is pushed onto stack
Step 4: Repeat step 2-3 until all symbols are scanned completely

DEPT OF CSE, ATMECE, MYSURU Page 34


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<math.h>
#include<string.h>
int s[30],op1,op2;
int top=-1,i;
char p[30],sym;
int op(int op1,char sym,int op2)
{
switch(sym)
{
case '+':return op1+op2;
case '-':return op1-op2;
case '*':return op1*op2;
case '/':return op1/op2;
case '%':return op1%op2;
case '^':
case '$':return pow(op1,op2);
}
return 0;
}
int main()
{
printf("\nEnter the valid postfix exp:");
scanf("%s",p);
for(i=0;i<strlen(p);i++)
{
sym=p[i];
if(sym>='0' &&sym<='9')
s[++top]=sym-'0';
else
{
op2=s[top--];
op1=s[top--];
s[++top]=op(op1,sym,op2);
}
DEPT OF CSE, ATMECE, MYSURU Page 35
VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

}
printf("\nThe result is %d",s[top]);
}

Output1
Enter the valid postfix exp:
23+
The result is 5

Output2
Enter the valid postfix exp:
123-4*+
The result is -3.

Output3
Enter the valid postfix exp:
623+-382/+*2$3+
The result is 52

Program outcome:
 Identify the applications of suffix expression.
 Familiarized with the methodology of suffix evaluation.
 Familiarized the operator precedence and associativity.

Viva Questions
 What is Suffix Expression?

DEPT OF CSE, ATMECE, MYSURU Page 36


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

5 b. Solving Tower of Hanoi problem with n disks

Program objective:
 Understand tower of Hanoi problem.
 Understand recursive functions and its disadvantages.

Algorithm:
MAIN FUNCTION ()
Step 1: Read No of disks called n from keyboard.
Step 2: Check if n is not zero or a negative no. if yes display suitable message
else go to step3.
Step 3: Call tower of Hanoi function with n asparameter,
Step 4: Stop

TOWERS OF HANOI FUNCTION TO MOVE DISKS FROM A TO C


USING B ()
Step 1: If n is equal to 1 then move the single disk from A to C and stop
Step 2: Move the top n
-
Step 1 disks from A to B using c as auxiliary.
Step 3: Move the remaining disk from A to C.
Step 4: Move the n-1 disks from B to C using as auxiliary.

THEORY

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a
number of disks of different sizes which can slide onto any rod. The puzzle starts with the
disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making
a conical shape.

The program objective of the puzzle is to move the entire stack to another rod, obeying
the following simple rules:
 Only one disk can be moved at a time.

 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.
 No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks

DEPT OF CSE, ATMECE, MYSURU Page 37


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
int count=0,n;
int tower(int n,char s,char t,char d)
{
if(n==1)
{
printf("\n Move disc 1 from %c to %c",s,d);
count++;
return 1;
}
tower(n-1,s,d,t);
printf("\n Move disc %d from %c to %c",n,s,d);
count++;
tower(n-1,t,s,d);
}
int main( )
{
printf("\n Enter the no. of discs:");
scanf("%d",&n);
tower(n,'A','B','C');

Output
Enter the no. of discs:
3
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C

DEPT OF CSE, ATMECE, MYSURU Page 38


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Program outcome:
 Identify the application of Tower of Hanoi problem.
 Implement the methodology to solve Tower of Hanoi problem.
 Implement the given problem using recursive function.

Viva Questions
 How do you solve the problem of the Tower of Hanoi using recursion?
 What is recursion? And what is tower of Hanoi problem?

DEPT OF CSE, ATMECE, MYSURU Page 39


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 6
Design, develop and implement a menu driven Program in C for the
following operations on Circular QUEUE of Characters (Array
Implementation of Queue with maximum size MAX)
a Insert an Element on to Circular QUEUE
b Delete an Element from Circular QUEUE
c Demonstrate Overflow and Underflow situations on Circular QUEUE
d Display the status of Circular QUEUE
e Exit
Support the program with appropriate functions for each of the above
operations

Program objective:
 Understand the working of circular queue
 Know the advantages of circular queue over liner queue.
 Understand the insertion and deletion operation on circular queue.
 Understand overflow and underflow conditions in circular queue.

ALGORITHM:
Step1: Initialize front and rear pointer and also count
front->0,count<-0,rear<- -1

Step2: Insert an element into queue before check overflow condition


Count=max
Insert an element rear<-(rear+1) %max
q[rear]<-item and count=count+1

Step3: Delete an element from queue .check underflow condition


Count=0 underflow condition. Count<-count-1
Item<-q[front]Deleted element

Step4: Display contents of queue. Number of elements represents count.


Check empty queue condition before displaying an element

DEPT OF CSE, ATMECE, MYSURU Page 40


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last
node is connected back to the first node to make a circle.

It is also called FIFO structure. Elements are added at the rear end and the elements are deleted
at front end of the queue. The queue is considered as a circular queue when the positions 0 and
MAX-1 are adjacent.

Fig6-circular queue

The limitation of simple queue is that even if there is a free memory space available in the
simple queue we cannot use that free memory space to insert element. Circular Queue is
designed to overcome the limitation of Simple Queue.

DEPT OF CSE, ATMECE, MYSURU Page 41


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#define MAX 4
int ch, front = 0, rear = -1, count=0;
char q[MAX], item;
void insert()
{
if(count == MAX)
printf("\nQueue is Full");
else
{
rear = (rear + 1) % MAX;
q[rear]=item;
count++;
}
}
void del()
{
if(count == 0)
printf("\nQueue is Empty");
else
{
if(front > rear && rear==MAX-1)
{
front=0; rear=-1; count=0;
}
else
{
item=q[front];
printf("\nDeleted item is: %c",item);
front = (front + 1) % MAX;
count--;
}
}

DEPT OF CSE, ATMECE, MYSURU Page 42


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void display()
{
int i, f=front, r=rear;
if(count == 0)
printf("\nQueue is Empty");
else
{
printf("\nContents of Queue is:\n");
for(i=f; i<=r; i++)
{
printf("%c\t", q[i]);
f = (f + 1) % MAX;
}
}
void main()
{
do{
printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit");
printf("\nEnter the choice: ");
scanf("%d", &ch);
flushall();
switch(ch)
{
case 1: printf("\nEnter the character item to be inserted: ");
scanf("%c", &item);
insert();
break;
case 2: del();
break;
case 3:display();
break;
case 4: exit(0);
break;
}
}
while(ch!=4);
}

DEPT OF CSE, ATMECE, MYSURU Page 43


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: C
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: D
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
ABCD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: F
Queue is Full
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
CD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: K
1. Insert 2. Delete
Enter the choice: 3

DEPT OF CSE, ATMECE, MYSURU Page 44


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Contents of Queue is:


CDK
1. Insert 2. Delete 3. Display 4.Exit
Enter the choice: 4

Program outcome:
 Identify the applications of circular queue.
 Implement insert and delete operations on circular queue.

Viva Questions:
 What is a queue ?what are applications of queue?
 What is Circular Queue? What is the difference between a Stack and a Queue?

DEPT OF CSE, ATMECE, MYSURU Page 45


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 7
Design, Develop and Implement a menu driven Program in C for the
following operations on Singly Linked List (SLL) of Student Data with the
fields: USN, Name, Branch, Sem, PhNo
a Create a SLL of N Students Data by using front insertion.
b Display the status of SLL and count the number of nodes in it
c Perform Insertion and Deletion at End of SLL
d Perform Insertion and Deletion at Front of SLL
e Demonstrate how this SLL can be used as STACKandQUEUE
f Exit

Program objective:
 Understand the Singly Linked List (SLL) data structures.
 Understand the methodology to insert and delete the element at the frontof
SLL.
 Understand the methodology to insert and delete the element at the endof
SLL.
 Get the knowledge of how SLL and be used as both stack and queue.

Algorithm
Step 1: declare structure of node create emptylist
head->null
Step2: Insert at front end
head<-null
returntemp
if list is empty
temp->link=head
return head
Step 3:Insert at rear end
head=null
returntemp
if list is empty
cur->head
while(cur!=null)
cur=cur->link
cur->link=temp;
return head

DEPT OF CSE, ATMECE, MYSURU Page 46


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Step 4: Delete at front end


head->link=null;
return null
if list has only one node
cur=head
head=head->link
free(cur)
Step 5:Delete at Rear end
head->link=null
return null
if only one node
cur<-head
while(cur!=null)
prev<-cur, cur=cur<-link;
free(cur);

DEPT OF CSE, ATMECE, MYSURU Page 47


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
Linked List is a linear data structure and it is very common data structure which consists of
group of nodes in a sequence which is divided in two parts. Each node consists of its own data
and the address of the next node and forms a chain. Linked Lists are used to create trees and
graphs.

In any single linked list, the individual element is called as "Node". Every "Node" contains two
fields, data and next. The data field is used to store actual value of that node and next field is
used to store the address of the next node in the sequence.

The graphical representation of a node in a single linked list is as follows...

Fig-7 Graphical Representation of Linked List


In a single linked list, the address of the first node is always stored in a reference node known
as "front" (Some times it is also known as "head").Always next part (reference part) of the last
node must be NULL.

They are a dynamic in nature which allocates the memory when required.
 Insertion and deletion operations can be easily implemented.
 Stacks and queues can be easily executed.
 Linked List reduces the access time.
 Linked lists are used to implement stacks, queues, graphs, etc.
 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don’t need to know the size in advance.

Advantages over arrays


1) Dynamic size
2) Ease of insertion/deletion

Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the
first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.

DEPT OF CSE, ATMECE, MYSURU Page 48


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int count=0;
struct node
{
int sem;
unsigned long long int phno;
char name[20],branch[10],usn[20];
struct node *next;
}
*first=NULL,*last=NULL,*temp=NULL, *temp1;

void create()
{
int sem;
unsigned long long int phno;
char name[20],branch[10],usn[20];
temp=(struct node*)malloc(sizeof(structnode));
printf("\n Enter usn,name, branch, sem, phno of student :\n ");
scanf("%s %s %s %d %llu", usn, name,branch, &sem,&phno);
strcpy(temp->usn,usn);
strcpy(temp->name,name);
strcpy(temp->branch,branch);
temp->sem = sem;
temp->phno = phno;
temp->next=NULL;
count++;
}

void insert_atfirst()
{
if (first == NULL)
{
create();
first = temp;
last = first;
}

DEPT OF CSE, ATMECE, MYSURU Page 49


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

else
{
create();
temp->next = first;
first = temp;
}
}

void insert_atlast()
{
if(first==NULL)
{
create();
first = temp;
last = first;
}
else
{
create();
last->next = temp;
last = temp;
}
}

void display()
{
temp1=first;
if(temp1 == NULL)
{
printf("List empty to display \n");
return;
}
printf("\n Linked list elements from begining : \n");
while (temp1!= NULL)
{
printf("%s\t %s \t%s\t %d \t%llu\n", temp1->usn,
temp1->name,temp1->branch,temp1->sem,temp1->phno );
temp1 = temp1->next;
}
printf(" No of students = %d\n ", count);
}

DEPT OF CSE, ATMECE, MYSURU Page 50


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

int deleteend()
{
struct node *temp;
temp=first;
if(temp->next==NULL)
{
printf("%s\t %s \t%s\t %d \t%llu\n", last->usn,
last->name,last->branch, last->sem, last->phno );
free(temp);
first=NULL;
}
else
{
while(temp->next!=last)
temp=temp->next;
printf("%s\t %s \t%s\t %d\t %llu\n", last->usn,
last->name,last->branch, last->sem, last->phno );
free(last);
temp->next=NULL;
last=temp;
}
count--;
return 0;
}

int deletefront()
{
struct node *temp;
temp=first;
if(temp->next==NULL)
{
printf("%s \t%s \t %s \t %d \t%llu\n", last->usn,
last->name,last->branch, last->sem, last->phno );
free(temp);
first=NULL;
return 0;
}
else
{
first=temp->next;
printf("%s \t%s \t%s \t%d \t %llu\n", temp->usn,
temp->name,temp->branch,temp->sem, temp->phno );

DEPT OF CSE, ATMECE, MYSURU Page 51


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

free(temp);
}
count--;
return 0;
}

void main()
{
int ch,n,i;
first=NULL;
temp = temp1 = NULL;
while (1)
{
printf("\n-----------------MENU ---------------------- \n");
printf("\n 1 create a SLL of n emp");
printf("\n 2 - Display from beginning");
printf("\n 3 - Insert at end");
printf("\n 4 - delete at end");
printf("\n 5 - Insert at beg");
printf("\n 6 - delete at beg");
printf("\n 7 - exit\n");
printf(" ------------------------------------------- \n");
printf("\n Enter choice : \n");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\n Enter no of students : \n");
scanf("%d", &n);
for(i=0;i<n;i++)
insert_atfirst();
break;
case 2:
display();
break;
case 3:
insert_atlast();
break;
case 4:
deleteend();
break;
case 5:

DEPT OF CSE, ATMECE, MYSURU Page 52


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

insert_atfirst();
break;
case 6:
deletefront();
break;
case 7:
exit(0);
default: printf("wrong choice\n");
}
}
}

Output

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------
Enter choice :
2
List empty to display
-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

DEPT OF CSE, ATMECE, MYSURU Page 53


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter choice :
1

Enter no of students :
2

Enter usn,name, branch, sem, phno of student :


4ad16cs022 harsha cs 3 9912367789

Enter usn,name, branch, sem, phno of student :


4ad16cs024 deepak cs 3 9538218822

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
2

Linked list elements from begining :


4ad16cs024 deepak cs 3 9538218822
4ad16cs022 harsha cs 3 9912367789
No of students = 2
-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg

DEPT OF CSE, ATMECE, MYSURU Page 54


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
3

Enter usn,name, branch, sem, phno of student :


4ad16cs011 bharath cs 3 9912698467

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
2

Linked list elements from begining :


4ad16cs024 deepak cs 3 9538218822
4ad16cs022 harsha cs 3 9912367789
4ad16cs011 bharath cs 3 9912698467
No of students = 3
-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg

DEPT OF CSE, ATMECE, MYSURU Page 55


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

7 - exit
-------------------------------------------

Enter choice :
5

Enter usn,name, branch, sem, phno of student :


4ad16cs033 jayakumar cs 3 8903478345

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
2

Linked list elements from begining :


4ad16cs033 jayakumar cs 3 8903478345
4ad16cs024 deepak cs 3 9538218822
4ad16cs022 harsha cs 3 9912367789
4ad16cs011 bharath cs 3 9912698467
No of students = 4

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg

DEPT OF CSE, ATMECE, MYSURU Page 56


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
4
4ad16cs011 bharath cs 3 9912698467

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
2

Linked list elements from begining :


4ad16cs033 jayakumar cs 3 8903478345
4ad16cs024 deepak cs 3 9538218822
4ad16cs022 harsha cs 3 9912367789
No of students = 3

-----------------MENU----------------------
1 create a SLL of n emp
2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit

DEPT OF CSE, ATMECE, MYSURU Page 57


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

-------------------------------------------

Enter choice :
6
4ad16cs033 jayakumar cs 3 8903478345

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
2

Linked list elements from begining :


4ad16cs024 deepak cs 3 9538218822
4ad16cs022 harsha cs 3 9912367789
No of students = 2

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

DEPT OF CSE, ATMECE, MYSURU Page 58


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter choice :
8
wrong choice

-----------------MENU----------------------

1 create a SLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
-------------------------------------------

Enter choice :
7

Program outcome :
 Implement Singly Linked List.
 Implement insertion at the front and end of SLL.
 Implement deletion at the front and end of SLL.
 Identify the applications of SLL.
 Familiarized how SLL can be used as both stack and queue.

Viva Questions :
 What is a Linked List and What are its types? What is a node?
 What are the parts of a linked list? What are the advantages of linked list?
 Mention what is traversal in linked lists?

DEPT OF CSE, ATMECE, MYSURU Page 59


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 8
Design, Develop and Implement a menu driven Program in C for the
following operations on Doubly Linked List (DLL) of Employee Data with
the fields: SSN, Name, Dept, Designation,Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue
f. Exit

Program objective:
 Understand the Doubly Linked List (DLL) data structures.
 Understand the methodology to insert and delete the element at the frontof
DLL.
 Understand the methodology to insert and delete the element at the endof
DLL.
 Get the knowledge of how DLL and be used as double ended queue.

Algorithm
Insertion at front end of list.
Step 1: Allocate memory for temp node and assign values to node
Step2: if list is empty, temp is attached to list directly
head=null
returntemp
if list is not empty
temp->rlink=head
head->llink=temp
return head

Insertion at rear end of list.


Step1: Read node information and allocate memory for temp node
Step2: traverse the cur node upto to end of list then attach node cur to temp
cur->rlink=temp;
temp->llink=cur
Step 3:return starting address of list

DEPT OF CSE, ATMECE, MYSURU Page 60


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

return head;

Delete from front end of list.


Step 1: check if list has only one node
head=NULL;
return null;
if list is empty
head->rlink=NULL
return NULL;
if list has o0nly one node
Step 2:otherwise first node address is shifted to next node
cur=head
head=head->rlink
free(cur)
Step 3: return starting address of list
return head

Delete node from rear end


Step 1: two pointers requires one is cur and prev
Cur is one which points, node to be deleted.

Step 2: Traverse the cur node upto end of list before updating current pointer save
the
Address to prev pointer.
While(cur->rlink!=null)
{
prev=cur;
cur=cur->rlink;
}
prev->rlink=null;
cur->llink=null;
free(cur);

Step3: return starting address of the list

DEPT OF CSE, ATMECE, MYSURU Page 61


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
 In computer science, a doubly linked list is a linked data structure that consists of a set
of sequentially linked records called nodes.

 Each node contains two fields, called links, that are references to the previous and to
the next node in the sequence of nodes. The beginning and ending nodes' previous and
next links, respectively, point to some kind of terminator, typically a sentinel node or
null, to facilitate traversal of the list. If there is only one sentinel node, then the list is
circularly linked via the sentinel node. It can be conceptualized as two singly linked
lists formed from the same data items, but in opposite sequential orders.

 A doubly linked list whose nodes contain three fields: an integer value, the link to the
next node, and the link to the previous node.

 The two node links allow traversal of the list in either direction. While adding or
removing a node in a doubly linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more
efficient (for nodes other than first nodes) because there is no need to keep track of the
previous node during traversal or no need to traverse the list to find the previous node,
so that its link can be modified.

DEPT OF CSE, ATMECE, MYSURU Page 62


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>

int count=0;

struct node
{
struct node *prev;
int ssn;
unsigned long long int phno;
float sal;
char name[20],dept[10],desg[20];
struct node *next;
}
*h,*temp,*temp1,*temp2,*temp4;

void create()
{
int ssn;
float sal;
unsigned long long int phno;
char name[20],dept[10],desg[20];
temp =(struct node *)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
printf("\n Enter ssn,name,department, designation, salary and phno
ofemployee :\n");
scanf("%d %s %s %s %f %llu", &ssn, name,dept,desg,&sal, &phno);
temp->ssn = ssn;
strcpy(temp->name,name);
strcpy(temp->dept,dept);
strcpy(temp->desg,desg);
temp->sal = sal;
temp->phno = phno;
count++;
}

DEPT OF CSE, ATMECE, MYSURU Page 63


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void insertbeg()
{
if (h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp->next = h;
h->prev = temp;
h = temp;
}
}

void insertend()
{
if(h==NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp1->next = temp;
temp->prev = temp1;
temp1 = temp;
}
}

void displaybeg()
{
temp2 =h;
if(temp2 == NULL)
{
printf("List empty to display \n");
return;
}

DEPT OF CSE, ATMECE, MYSURU Page 64


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

printf("\n Linked list elements from begining : \n");


while (temp2!= NULL)
{
printf("%d\t %s\t %s \t%s \t%f \t%llu\n", temp2->ssn,
temp2->name,temp2->dept,temp2->desg,temp2->sal, temp2->phno );
temp2 = temp2->next;
}
printf(" No of employees = %d\n", count);
}

int deleteend()
{
struct node *temp;
temp=h;
if(temp->next==NULL)
{
free(temp);
h=NULL;
return 0;
}
else
{
temp2=temp1->prev;
temp2->next=NULL;
printf("%d \t%s\t %s\t %s \t%f \t%llu\n", temp1->ssn,
temp1->name,temp1->dept,temp1->desg,temp1->sal,temp1->phno );
free(temp1);
}
count--;
return 0;
}

int deletebeg()
{
struct node *temp; temp=h;
if(temp->next==NULL)
{
free(temp);
h=NULL;
}

DEPT OF CSE, ATMECE, MYSURU Page 65


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

else
{
h=h->next;
printf("%d \t%s\t %s\t %s \t%f\t %llu\n", temp->ssn,
temp->name,temp->dept,temp->desg,temp->sal, temp->phno );
free(temp);
}
count--;
return 0;
}

void main()
{
int ch,n,i;
h=NULL;
temp = temp1 = NULL;
while (1)
{
printf("-----------------MENU -------------------- \n");
printf("\n 1- create a DLL of n emp");
printf("\n 2 - Display from beginning");
printf("\n 3 - Insert at end");
printf("\n 4 - delete at end");
printf("\n 5 - Insert at beg");
printf("\n 6 - delete at beg");
printf("\n 7 - exit\n");
printf(" ------------------------------------------ \n");
printf("\n Enter choice : \n");
scanf("%d", &ch);
switch (ch)

{
case 1:
printf("\n Enter no of employees : \n");
scanf("%d",&n);
for(i=0;i<n;i++)
insertend();
break; case 2:
displaybeg();
break;
case 3:
insertend();

DEPT OF CSE, ATMECE, MYSURU Page 66


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

break;
case 4:
deleteend();
break;
case 5:
insertbeg();
break;
case 6:
deletebeg();
break;
case 7:
exit(0);
default: printf("wrong choice\n");
}
}
}

DEPT OF CSE, ATMECE, MYSURU Page 67


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2
List empty to display

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
1

Enter no of employees :
2
Enter ssn,name,department, designation, salary and phno ofemployee :
120 harsha cs instructor 14000 9912378956

DEPT OF CSE, ATMECE, MYSURU Page 68


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter ssn,name,department, designation, salary and phno ofemployee :


121 sanjay cs programmer 15000 9538215567

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2

Linked list elements from begining :


120 harsha cs instructor 14000.000000 9912378956
121 sanjay cs programmer 15000.000000 9538215567
No of employees = 2

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at
end 5 - Insert at
beg 6 - delete
at beg 7 - exit
------------------------------------------
Enter choice :
3

DEPT OF CSE, ATMECE, MYSURU Page 69


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter ssn,name,department, designation, salary and phno ofemployee :


123 deepak cs instructor 14000 9534567812

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2

Linked list elements from begining :


120 harsha cs instructor 14000.000000 9912378956
121 sanjay cs programmer 15000.000000 9538215567
123 deepak cs instructor 14000.000000 9534567812
No of employees = 3
-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
5

DEPT OF CSE, ATMECE, MYSURU Page 70


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter ssn,name,department, designation, salary and phno ofemployee :


124 lohith cs lecturer 20000 9967834578

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2

Linked list elements from begining :


124 lohith cs lecturer 20000.000000 9967834578
120 harsha cs instructor 14000.000000 9912378956
121 sanjay cs programmer 15000.000000 9538215567
123 deepak cs instructor 14000.000000 9534567812
No of employees = 4

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------
Enter choice :
4
123 deepak cs instructor 14000.000000 9534567812

DEPT OF CSE, ATMECE, MYSURU Page 71


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2

Linked list elements from begining :


124 lohith cs lecturer 20000.000000 9967834578
120 harsha cs instructor 14000.000000 9912378956
121 sanjay cs programmer 15000.000000 9538215567
No of employees = 3

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
6

124lohith cs lecturer 20000.000000 9967834578

DEPT OF CSE, ATMECE, MYSURU Page 72


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
2

Linked list elements from begining :


120 harsha cs instructor 14000.000000 9912378956
121 sanjay cs programmer 15000.000000 9538215567
No of employees = 2

-----------------MENU--------------------

1- create a DLL of n emp


2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------
Enter choice :
8
wrong choice
-----------------MENU--------------------

DEPT OF CSE, ATMECE, MYSURU Page 73


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

1- create a DLL of n emp


2 - Display from beginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
------------------------------------------

Enter choice :
7
$

Program outcome:
 Implement Doubly Linked List.
 Implement insertion at the front and end of DLL.
 Implement deletion at the front and end of DLL.
 Identify the applications of DLL.
 Familiarized how DLL can be used as double ended queue.

Viva Questions:
 What are doubly linked lists?
 What is the difference between singly and doubly linked lists?
 What are the advantages of double linked list over single linked list?

DEPT OF CSE, ATMECE, MYSURU Page 74


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 9
Design, Develop and Implement a Program in C for the following operations
on Singly Circular Linked List (SCLL) with header nodes
a Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-
2xyz3
b Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and
store the result in POLYSUM(x,y,z)

Program objective: .
 Understand the working of Singly Circular Linked List (SCLL).
 Understand the use of header nodes.
 Understand the methodology to evaluate polynomial using SCLL.
 Understand the methodology to add two polynomial usingSCLL.

Algorithm:
Evaluate a Polynomial
Step1: allocate memory for newly created node assign values to that node
Step 2: attach newly created node to list in circular fashion.
Step3: Evaluate each node information up to header node

Addition of two Polynomial


Step1: Read exponent values and co-efficient values for each node
Step2: newly created node are attached to polynomials (p1, p2, p3)
Step3: Addition/Evaluation of list is performed
Step 5: Result is displayed

DEPT OF CSE, ATMECE, MYSURU Page 75


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
Circular Linked List:
In the circular linked list the last node of the list contains the address of the first node
and forms a circular chain.

Circular Linked List is a variation of Linked list in which the first element points to the
last element and the last element points to the first element. Both Singly Linked List and
Doubly Linked List can be made into a circular linked list.

Fig-8- Circular Linked List

DEPT OF CSE, ATMECE, MYSURU Page 76


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<math.h>
typedef struct node
{
int expo,coef;
struct node *next;
}
node;
node * insert(node *,int,int);
node * create();
node * add(node *p1,node *p2);
inteval(node *p1);
void display(node *head);
node *insert(node*head,int expo1,int coef1)
{
node *p,*q;
p=(node *)malloc(sizeof(node));
p->expo=expo1;
p->coef=coef1;
p->next=NULL;
if(head==NULL)
{
head=p;
head->next=head;
return(head);
}
if(p->expo==q->expo)
q->coef=q->coef+coef1;
else
{
p->next=q->next;
q->next=p;
}
return(head);
}

DEPT OF CSE, ATMECE, MYSURU Page 77


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

node *create()
{
int n,i,expo1,coef1;
node *head=NULL;
printf("\n\nEnter no of terms of polynomial==>");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEntercoef& expo==>");
scanf("%d%d",&coef1,&expo1);
head=insert(head,expo1,coef1);
}
return(head);
}
int eval(node *head)
{
node *p;
int x, ans=0;
printf("\n\nEnter the value of x=");
scanf("%d",&x);
p=head->next;
do
{
ans=ans+p->coef*pow(x,p->expo);
p=p->next;
}
while(p!=head->next);
return(ans);
}

DEPT OF CSE, ATMECE, MYSURU Page 78


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void display(node *head)


{
node *p,*q;
int n=0;
q=head->next;
p=head->next;
do
{
n++;
q=q->next;
}
while(q!=head->next);
printf("\n\n\tThe polynomial is==>");
do
{
if(n-1)
{
printf("%dx^(%d) + ",p->coef,p->expo);
p=p->next;
}
else
{
printf(" %dx^(%d)",p->coef,p->expo); p=p->next;
}
n--;
}
while(p!=head->next);
}
void main()
{
int a,x,ch;
node *p1,*p2,*p3; p1=p2=p3=NULL;
while(1)
{
printf("\n\t----------------<< MENU >>--------------- ");
printf("\n\tPolynomial Operations :");
printf(" 1.Add");

DEPT OF CSE, ATMECE, MYSURU Page 79


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

printf("\n\t\t\t\t2.Evaluate");
printf("\n\t\t\t\t3.Exit");
printf("\n\t -------------------------------------------- ");
printf("\n\n\n\tEnter your choice==>");
scanf("%d",&ch);
switch(ch)
{
case 1 :
p1=create();
display(p1);
p2=create();
display(p2);
p3=add(p1,p2);
display(p3);
break;
case 2 :
p1=create();
display(p1);
a=eval(p1);
printf("\n\nValue of polynomial=%d",a);
break;
case 3 :
exit(0);
break;
default :
printf("\n\n\tinvalid choice");
break;
}
}
}

DEPT OF CSE, ATMECE, MYSURU Page 80


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output
-----------------<< MENU >>---------------
Polynomial Operations : 1.Add 2.Evaluate
3.Exit
Enter your choice==>1
Enter no of terms of polynomial==>3
Enter coef& expo==>
4
3
Enter coef& expo==> 2 2
Enter coef& expo==> 5 1
The polynomial is==>5x^(1) + 2x^(2) + 4x^(3)
Enter no of terms of polynomial==>3
Enter coef& expo==> 4 1
Enter coef& expo==>
3
2
Enter coef& expo==> 5 3
The polynomial is==>4x^(1) + 3x^(2) + 5x^(3)
Addition of polynomial==>
The polynomial is==>9x^(1) + 5x^(2) + 9x^(3)
Enter your choice==>2
Enter no of terms of polynomial==>3
Enter coef& expo==>
3
1

Enter coef& expo==> 4 2


Enter coef& expo==> 5 4
The polynomial is==>3x^(1) + 4x^(2) + 5x^(4)
Enter the value of x=2
Value of polynomial=102
Enter your choice==>3
exit

DEPT OF CSE, ATMECE, MYSURU Page 81


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Program outcome :
 Implement Singly Circular Linked List (SCLL) using header node.
 Identify the application of SCLL.
 Familiarized with the methodology of polynomial evaluation and polynomial
addition using SCLL.

Viva Questions:
 What is circular linked list.?
 What are Advantages and Disadvantages of Circular Linked List?

DEPT OF CSE, ATMECE, MYSURU Page 82


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 10
Design, Develop and Implement a menu driven Program in C for the
following operations on Binary Search Tree (BST) of Integers
A Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
B Traverse the BST in In-order, Preorder and Post Order
C Search the BST for a given element (KEY) and reportthe appropriate
message
D Delete an element (ELEM) from BST
E Exit

Program objective:
 Understand the concept of Binary Search Tree (BST).
 Understand the different traversal method on BST.
 Get to know the methodology of searching a key element in BST.
 Understand the methodology of deleting an element from BST.

Algorithm:
Preorder Traversal
Step 1: Display root information
Step2: Traverse left sub tree in preorder
Step 3: Traverse right sub tree in preorder

In order Traversal
Step 1: Traverse the left sub tree in order
Step 2: Display root information
Step3: Traverse right sub tree in order

Post order Traversal


Step 1: traverse the left sub tree in post order
Step 2: traverse the right sub tree in post order
Step 3: Display root information

DEPT OF CSE, ATMECE, MYSURU Page 83


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties
 The left sub-tree of a node has key less than or equal to its parent node’s V key.
 The right sub-tree of a node has key greater than or equal to its parent node'skey.

Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-tree and
right sub-tree and can be defined as

left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

Fig 9-Example of BST

Following are basic primary operations of a tree which are following.


 Search − search an element in a tree.
 Insert − insert an element in a tree.
 Preorder Traversal − traverse a tree in a preordermanner.
 Inorder Traversal − traverse a tree in an inorder manner.
 Postorder Traversal − traverse a tree in a postorder manner.

DEPT OF CSE, ATMECE, MYSURU Page 84


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int flag=0;
typedefstruct BST
{
int data;
struct BST *lchild,*rchild;
}node;
void insert(node*,node*);
void inorder(node*);
void preorder(node*);
void postorder(node*);
node *search(node*,int,node**);
void main()
{
int
choice;
int ans=1;
int key;
node*new_node,*root,*temp,*parent;
node*get_node();
root=NULL;
printf("\n program for binary search tree");
do{
printf("\n1.Create");
printf("\n2.Search");
printf("\n3.Recursive Traversals");
printf("\n4.Exit");
printf("\nEnter your Choice=");
scanf("%d",&choice);
switch(choice)
{
case 1:

DEPT OF CSE, ATMECE, MYSURU Page 85


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

do{
new_node=get_node();
printf("\nEnter the element=");
scanf("%d",&new_node->data);
if(root==NULL)
root=new_node;
else
insert(root,new_node);
printf("\nWant to enter more elements?(1/0)");
scanf("%d",&ans);
}
while(ans);
break;
case 2:
printf("\nEnter elements to be searched=");
scanf("%d",&key);
temp=search(root,key,&parent);
if(flag==1)
{
printf("\nParent of node %d is %d",temp->data,parent->data);
}
else
{
printf("\nThe %d elements is not present",key);
}
flag=0;
break;
case 3:
if(root==NULL)
printf("Tree is not created");
else
{
printf("\nTheinorder display=");

DEPT OF CSE, ATMECE, MYSURU Page 86


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

inorder(root);

printf("\nThe preorder display=");


preorder(root);
printf("\nThepostorder display=");
postorder(root);
}
break;
}
}
while(choice!=4);
}
node*get_node()
{
node*temp;
temp=(node*)malloc(sizeof(node));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void insert(node*root,node*new_node)
{
if(new_node->data<root->data)
{
if(root->lchild==NULL)
root->lchild=new_node;
else
insert(root->lchild,new_node);
}
if(new_node->data>root->data)
{
if(root->rchild==NULL)
root->rchild=new_node;
else

DEPT OF CSE, ATMECE, MYSURU Page 87


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

node *search(node*root,intkey,node**parent)
{
node*temp;
temp=root;
while(temp!=NULL)
{
if(temp->data==key)
{
printf("\nThe %d elements is present",temp->data);
flag=1;
return temp;
}
*parent=temp;
if(temp->data>key)
temp=temp->lchild;
else
temp=temp->rchild;
}
return NULL;
}
void inorder(node*temp)
{
if(temp!=NULL)
{
inorder(temp->lchild);
printf("%d\t",temp->data);
inorder(temp->rchild);
}
preorder(temp->lchild);
preorder(temp->rchild);

if(temp!=NULL)
{
printf("%d\t",temp->data);
}
}

DEPT OF CSE, ATMECE, MYSURU Page 88


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

void postorder(node*temp)
{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d\t",temp->data);
}
}

DEPT OF CSE, ATMECE, MYSURU Page 89


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output
program for binary search tree
1.Create
2. Search
3. Recursive Traversals
4.Exit
Enter your Choice= 1
Enter the element=15
Want to enter moreelements?(1/0)1
Enter the element=25
Want to enter moreelements?(1/0)1
Enter the element=35
Want to enter moreelements?(1/0)1
Enter the element=45
Want to enter moreelements?(1/0)1
Enter the element=5
Want to enter moreelements?(1/0)1
Enter the element=7
Want to enter more elements?(1/0)0
1.Create
2. Search
3. Recursive Traversals
4.Exit
Enter your choice=2
Enter elements to be searched=7
The 7 element is present
parent of node 7 is 5
1.Create
2. Search
3. Recursive Traversals
4.Exit
Enter your choice=2
Enter elements to be searched=88
the 88 element is not present

DEPT OF CSE, ATMECE, MYSURU Page 90


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice=3
The inorder display =5 7 15 25 35 45
The preorder display=15 5 7 25 35 45
The postorder display=7 5 45 35 25 15
1.Create
2. Search
3. Recursive Traversals
4.Exit
Enter your choice=4
Program outcome:
 Implement Binary Search Tree (BST).
 Implement the different traversal methodology on BST.
 Familiarized with the methodology to search a key element in BST.
 Implement the methodology to delete an element from BST.
 Identify the applications of BST

Viva Questions:
 What are binary trees?
 Explain Binary Search Tree
 How to check if a given Binary Tree is BST or not?
 What is the minimum number of nodes that a binary tree can have?
 What are the different types of traversing?
 Define pre-order traversal?
 Define post-order traversal?
 Define in -order traversal?

DEPT OF CSE, ATMECE, MYSURU Page 91


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 11
Design, develop and implement a Program in C for the following operations
on Graph (G) of Cities
a Create a Graph of N cities using Adjacency Matrix.
b Print all the nodes reachable from a given starting node in a digraph
using BFS method
c Check whether a given graph is connected or not usingDFS
Method.

Program objective:
 Understand the concept of trees and adjacency matrix.
 Understand the concept of connected graph.
 Understand the Breath First Search (BFS) and Depth First Search(DFS)
traversal methodologies.

Algorithm:

Step 1: Initialize front,rear,visit and number of nodes


Step 2: Read adjacency matrix for graph
Step 3: select source vertex from graph i.e v
Step 4: source node is added into queue and cover all the nodes (adjacent) to v.
Once it is covered adjacent/traversed mark as visited.
Step 5: Read next vertex from queue and cover all the nodes .if it is not visited,
visit the nodes.
Step 6: Repeat the process 3-5 until all nodes are covered in queue

DEPT OF CSE, ATMECE, MYSURU Page 92


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

THEORY
BFS first visits all the vertices that are adjacent to a starting vertex. Every time it adds the
adjacent vertex to a queue array q. On each successive iteration of the algorithm, the next
vertex on the queue is examined to see if there are any unvisited vertices adjacent to it which
can be added to the queue. Whenever a new vertex is taken from the queue, it is marked as a
visited node in the visited array.

Applications of BFS:
 To check connectivity of a graph (number of times queue becomes empty tellsthe
number of components in the graph)
 To check if a graph is acyclic. (no cross edges indicates no cycle)
 To find minimum edge path in a graph

Depth first search is a graph algorithm required for processing vertices or edges of a
graph in a systematic fashion. Depth first search starts visiting vertices of a graph at an
arbitrary vertex by marking it as having been visited. On each iteration, the algorithm proceeds
to an unvisited vertex that is adjacent to one it is currently in.

The algorithm backs up one edge to the vertex it came from and tries to continue
visiting unvisited vertices from there. The algorithm eventually halts after backing up to
starting vertex, with the latter being dead end. By then, all vertices in the same connected
component as the starting vertex have been visited. If unvisited vertices still remain, the depth
first search must be restarted at any one of them.

Here we use a STACK to trace the depth first search. We push a vertex onto the stack
when the vertex is reached for the first time, and we pop a vertex off the stack when it
becomes a dead end.

Applications of DFS:
 The two orderings are advantageous for various applications like topologicalsorting,
etc.
 To check connectivity of a graph (number of times stack becomes emptytells the
number of components in the graph)
 To check if a graph is acyclic. (no back edges indicates no cycle)
 To find articulation point in a graph

DEPT OF CSE, ATMECE, MYSURU Page 93


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int n,a[10][10],i,j,source,s[10],choice,count;
void bfs(int n,int a[10][10],int source,int s[])
{
int q[10],u;
int front=1,rear=1;
s[source]=1;
q[rear]=source;
while(front<=rear)
{
u=q[front];
front=front+1;
for(i=1;i<=n;i++)
if(a[u][i]==1 &&s[i]==0)
{
rear=rear+1;
q[rear]=i;
s[i]=1;
}
}
}
void dfs(int n,int a[10][10],int source,int s[])
{
s[source]=1;
for(i=1;i<=n;i++)
if(a[source][i]==1 && s[i]==0)
dfs(n,a,i,s);
}
int main()
{
printf("Enter the number of nodes : \n");
scanf("%d",&n);
printf("\n Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)

DEPT OF CSE, ATMECE, MYSURU Page 94


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

scanf("%d",&a[i][j]);

while(1)
{

printf("\n\n1.BFS\n 2.DFS\n 3.Exit\n");


printf("\nenter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n Enter the source :\n");
scanf("%d",&source);
for(i=1;i<=n;i++)
s[i]=0;
bfs(n,a,source,s);
for(i=1;i<=n;i++)
{
if(s[i]==0)
printf("\n The node %d is not reachable\n",i);
else
printf("\n The node %d is reachable\n",i);
}
break;
case 2:printf("\nEnter the source vertex :\n");
scanf("%d",&source);
count=0;
for(i=1;i<=n;i++)
s[i]=0;
dfs(n,a,source,s);
for(i=1;i<=n;i++)
if(s[i])
count=count+1;
if(count==n)
printf("\nThe graph is connected.");
else
printf("\nThe graph is not connected.");
break;
case 3: exit(0);

DEPT OF CSE, ATMECE, MYSURU Page 95


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

}
}
}

Output1

Enter the number of nodes


:4

Enter the adjacencymatrix


0010
1010
0000
0000

1. BFS
2. DFS
3. Exit

enter your choice


1

Enter the source :


1

The node 1 is reachable

The node 2 is not reachable

The node 3 is reachable

The node 4 is not reachable

1. BFS
2. DFS
3. Exit

enter your choice


2

DEPT OF CSE, ATMECE, MYSURU Page 96


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter the source vertex :


1

The graph is not connected.

1.BFS
2. DFS
3. Exit
enter your choice
3

Output2

Enter the number of nodes :


3

Enter the adjacencymatrix


011
000
000

1. BFS
2. DFS
3. Exit

enter your choice


1

Enter the source :


1

The node 1 is reachable

The node 2 is reachable

The node 3 is reachable

DEPT OF CSE, ATMECE, MYSURU Page 97


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

1. BFS
2. DFS
3. Exit

enter your choice


2

Enter the source vertex:


1

The graph is not connected.

1.BFS
2. DFS
3. Exit

enter your choice


3

Output3

Enter the number of nodes :


3

Enter the adjacencymatrix


010
001
100

1. BFS
2. DFS
3. Exit

enter your choice


1

DEPT OF CSE, ATMECE, MYSURU Page 98


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Enter the source :


1

The node 1 is reachable

The node 2 is reachable

The node 3 is reachable

1. BFS
2. DFS
3. Exit

enter your choice


2

Enter the source vertex:


1

The graph is connected.

1.BFS
2. DFS
3. Exit

enter your choice


3

DEPT OF CSE, ATMECE, MYSURU Page 99


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Program outcomes:
 Create graph using adjacency matrix.
 Implement Breadth First Search (BFS) and Depth First Search (DFS).
 Familiarized with connected graph.
 Identify the applications of graphs.

Viva Questions:
 What is a graph?
 What is a tree?
 What is BFS and DFS?
 Which data structures are used for BFS and DFS of a graph?

DEPT OF CSE, ATMECE, MYSURU Page 100


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

PROGRAM 12
Given a File of N employee records with a set K of Keys(4-digit) which
uniquely determine the records in file F. Assume that file F is maintained in
memory by a Hash Table(HT) of mmemory locations with L as the set of
memory addresses (2-digit) of locations in HT. Let the keys in K and
addresses in L are Integers.
Design and develop a Program in C that uses Hash function H: K->L as
H(K)=K mod m (remainder method), and implement hashing technique to
map a given key K to the address space L. Resolve the collision (if any) using
linear probing.

Program objective:
 Understand what is hashing and hashing function.
 Understand the concept of linear probing.
 Understand the concept of collision detection and avoidance using linear
probing.

Algorithm:
Step 1: Start
Step 2: Initialize all memory locations with some values to identity as space
a[i]=-1
Step 3: Read Employee key value .calculate hash key using remainder method
hk<-key%100
Step 4: Inserting Employee record using key
Inserting hash dull function
If(count=m)
If space is available for that key
If(H[k]==-1)
H[hk] <-key
If collision occurs, it can be solved using linear probing method.
Checking free space from key to end
for(i=hk+1;i<m;i++)
Checking free space from beginning to key value.
for(i=0;i<hk&& flag==0;i++)
Step 5: Display all memory location with index and employee key

DEPT OF CSE, ATMECE, MYSURU Page 101


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int create(int);
void linear_prob(int[], int, int);
void display (int[]);
void main()
{
int a[MAX],num,key,i;
int ans=1;
printf("collision handling by linear probing : \n");
for (i=0;i<MAX;i++)
{
a[i] = -1;
}
do
{
printf("\n Enter the data");
scanf("%4d", &num);key=create(num);
linear_prob(a,key,num);
printf("\n Do you wish to continue ? (1/0) ");
scanf("%d",&ans);
}

int create(intnum)
{
int key; key=num%100;
return key;
}
void linear_prob(int a[MAX], int key, intnum)
{
int flag, i, count=0;
int flag=0;
if(a[key]== -1)
{
a[key] = num;

DEPT OF CSE, ATMECE, MYSURU Page 102


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

}
else
{
printf("\nCollisionDetected...!!!\n");
i=0;
while(i<MAX)
{
if (a[i]!=-1)
count++;
i++;
}
printf("Collision avoided successfully using LINEAR PROBING\n");
if(count == MAX)
{
printf("\n Hash table is full");
display(a);
exit(1);
}
for(i=key+1; i<MAX; i++)
if(a[i] == -1)
{
a[i] = num;
flag =1; break;
}
//for(i=0;i<key;i++)
while((i<key) && (flag==0))
{
i=0;
i++;
}
}
}

DEPT OF CSE, ATMECE, MYSURU Page 103


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

if(a[i] == -1)
{
a[i] = num;
flag=1; break;
}

void display(int a[MAX])


{
inti,choice;
printf("1.Display ALL\n 2.Filtered Display\n");
scanf("%d",&choice);
if(choice==1)
{
printf("\n the hash table is\n");
for(i=0; i<MAX; i++)
printf("\n %d %d ", i, a[i]);
}
else
{
printf("\n the hash table is\n");
for(i=0; i<MAX; i++)
if(a[i]!=-1)
{
printf("\n %d %d ", i, a[i]);
continue;
}
}
}

DEPT OF CSE, ATMECE, MYSURU Page 104


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Output
collision handling by linear probing :
Enter the data1234
Do you wish to continue ? (1/0) 1
Enter the data2548
Do you wish to continue ? (1/0) 1
Enter the data3256
Do you wish to continue ? (1/0) 1
Enter the data1299
Do you wish to continue ? (1/0) 1
Enter the data1298
Do you wish to continue ? (1/0) 1
Enter the data1398
Collision Detected...!!!
Collision avoided successfully using LINEAR PROBING
Do you wish to continue ? (1/0) 0
1.Display ALL
2.Filtered Display
the hash table is
0 1398
34 1234
48 2548
56 3256
98 1298
99 1299

DEPT OF CSE, ATMECE, MYSURU Page 105


VTU Connect Android App Download Now On Google Play Store
VTU Connect Android App Download Now On Google Play Store
DATA STRUCTURES LABORATORY 18CSL38

Program outcome:
 Implement hashing function.
 Implement linear probing.
 Familiarized the concept of collusion detection and avoidance and detection
using linear probing.
 Identify the application of hashing and linear probing.

Viva Questions:
 What is Hashing?
 What is Linear Probing?

DEPT OF CSE, ATMECE, MYSURU Page 106


VTU Connect Android App Download Now On Google Play Store

You might also like