Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ds Narjjis

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 98

Degree Engineering

A Laboratory Manual for

Data Structures
(3130702)

[ B.E. (Computer Engineering) : Semester - 3 ]

Enrolment No
Name
Branch
Academic Term
Institute Name

Directorate of Technical Education,


Gandhinagar, Gujarat
Government Engineering College, Bhavnagar
Department of Computer Engineering

CERTIFICATE

This is to certify that Mr./Ms.

Enrollment No. of B.E. Semester - III from Computer

Engineering Department of this Institute (GTU Code: _021 ) has satisfactorily

completed the Practical / Tutorial work for the subject Data structure (3130702)

for the academic year 2023-24.

Place:

Date:

Signature of Course Faculty Head of the Department


Data Structure (3130702) Enrollment No

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed
to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Data Structures is a core course in all computer science undergraduate curricula. The course is
the basis for understanding several data structures and also algorithms that operate on them. The
course forms the foundation for almost all computer science subjects: compilers, operating
systems, databases, AI and software engineering. The course comes with a lab in most
universities in India. The associated lab in university curricula focuses on implementation of
algorithms operating on the data structures, i.e., coding programs on the data structures and
algorithms.
Data Structure (3130702) Enrollment No
DTE’s Vision

 To provide globally competitive technical education


 Remove geographical imbalances and inconsistencies
 Develop student friendly resources with a special focus on girls’ education and support
to weaker sections
 Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision
To transform the students into good human beings, employable engineering graduates
and continuous learners by inculcating human values and imparting excellence in technical
education.

Institute’s Mission
To provide education to students from the local and rural areas, so that they become enlightened
individuals and improve the living standards of their families, and their contribution to industry
and society. To foster a learning environment with technology integration and individual
attention, so that the students imbibe quality technical knowledge, skill-development and
character building.

Department’s Vision

To achieve excellence for providing value based education in computer science and Information
Technology through innovation, team work and ethical practices.

Department’s Mission

 To produce graduates according to the need of industry, government, society and


scientific community and to develop partnership with industries, government
agencies and R & D Organizations for knowledge sharing and overall development of
faculties and students.
 To motivate students/graduates to be entrepreneurs.
 To motivate students to participate in reputed conferences, workshops,
symposiums, seminars and related technical activities.
 To impart human and ethical values in our students for better serving of society.
Data Structure (3130702) Enrollment No

Programme Outcomes (POs)

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


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. 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.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. 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.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. 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
Data Structure (3130702) Enrollment No

Program Specific Outcomes (PSOs)


 An ability to design solutions by simulating computer engineering problems in absence
of real time environment.
 An ability to learn and use of open source tools in the areas like operating systems,
computer programming, computer networks and database management.
 An ability to face competitive examinations for higher education and PSUs.

Program Educational Objectives (PEOs)

 Have careers in industry, research & academics focusing on the application of the
information technologies and take leadership positions in the industry and also
initiate businesses offering innovative solutions.
 Capable of adapting to new technologies and constantly upgrade their skills with
an attitude towards lifelong learning.
 Act conscientiously about the potentials and the responsibilities of the
computing profession in the context of science, technology, society and
humanity.
Data Structure (3130702) Enrollment No

Practical – Course Outcome matrix

Course Outcomes (COs)


Define and classify various data structures, storage structures and common
CO_3130702.1
operations on them
Create various linear data structures with their representation and perform
CO_3130702.2
different operations on them
Create various nonlinear data structures with their representation and
CO_3130702.3
perform different operations on them
CO_3130702.4 Apply various searching sorting techniques on data set
Solve the given a problem using an appropriate data structure to achieve
CO_3130702.5 optimal performance and compare its performance with other possible data
structures

Sr. CO CO CO CO CO
Practical Outcome/Title of experiment
No. 1 2 3 4 5
1. Classification of Data Structure and Stack
1.1 Classify various data structures
1.2 Implement a program for stack that performs
following operations using array. (a) PUSH (b)
POP
(c) PEEP (d) CHANGE (e) DISPLAY
1.3 Implement a program to convert infix notation to √ √ √
postfix notation using stack.
1.4 Write a program to implement Tower of Hanoi
problem.
1.5 Identify widely used application which use stack
data structure for implementation of its important
feature.
2. Queue
2.1 Write a program to implement QUEUE using arrays
that performs following operations (a) INSERT (b)
DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using
arrays that performs following operations. (a) √ √
INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which use Queue
data structure for implementation of its important
feature.
3. Singly linked list
3.1 Write a menu driven program to implement
√ √
following operations on the singly linked list.
Data Structure (3130702) Enrollment No

(a) Insert a node at the front of the linked list.


(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in
ascending order.(according to info. Field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.
3.2 Write a program to implement stack using linked
list.
3.3 Write a program to implement queue using linked
list.
4. Doubly linked list

4.1 Write a program to implement following operations


on the doubly linked list.
(a) Insert a node at the front of the linked list.
√ √
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

5. Circular linked list


5.1 Write a program to implement following operations
on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
√ √
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which use Linked
List for implementation of its important feature.

6. Tree
6.1 Write a program which create binary search tree.
6.2 Implement recursive tree traversing methods in-
order, pre-order and post-order traversal
√ √
6.3 Identify widely used application which use Tree
data structure for implementation of its important
feature.

7. Graph
7.1 Write a program to perform BFS and DFS on
given graph.
7.2 Identify widely used application which use Graph √ √
data structure for implementation of its important
feature.
Data Structure (3130702) Enrollment No

8. Searching
8.1 Write a program to implement Linear Search.
8.2 Write a program to implement Binary Search.
8.3 Identify widely used application which use √ √
Searching technique for implementation of its
important feature.

9. Sorting
9.1 Write a program to implement Quick Sort
9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
√ √
9.4 Identify widely used application which use
Sorting technique for implementation of its
important
feature.
10 Hashing and File Structure

10.1 Write a program to create hash table and


handle the collision using linear probing.
10.2 Write a program to demonstrate the file
primitives such as fopen, fclose, fprintf. √ √
10.3 Identify widely used application which use
Hashing technique for implementation of
its
Important feature.
Data Structure (3130702) Enrollment No

Industry Relevant Skills

The following industry relevant competencies are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to classify data structures and identify storage representation of
primitive and non-primitive data structures
2. Will be able to implement various operations on Stack, Queue, Link list, Tree,
Graph, Hashing and File operations.
3. Will be able to understand need of sorting and searching for various applications
4. Will be able to apply various data structure to design real time applications
in efficient manner.

Guidelines for Faculty members

1. Teacher should provide the guideline with demonstration of practical to the


students with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students
before starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students

1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
2. Students will have to perform experiments on computer system on which C/C++ compiler
is installed to execute programs of data structure.
3. Students should develop programs and execute all the programs using C/C++ compiler.
Students have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.
Data Structure (3130702) Enrollment No

Common Safety Instructions

Students are expected to

1. switch on the PC carefully (not to use wet hands)


2. shutdown the PC properly at the end of your Lab
3. carefully handle the peripherals (Mouse, Keyboard, Network cable etc)
4. use Laptop in lab after getting permission from Teacher
5. carefully handle all lab resources
Data Structure (3130702) Enrollment No

Index
(Progressive Assessment Sheet)

Date
Date of Assessme Sign.
Sr. Page of Remar
Objective(s) of Experiment submiss nt Marks
No. No. perfor ks
ion of
mance
Teacher
with date

1. Classification of Data Structure and Stack


1.1 Classify various data structures
1.2 Implement a program for stack that
performs following operations using array.
(a) PUSH (b) POP (c) PEEP (d) CHANGE
(e) DISPLAY
1.3 Implement a program to convert infix
notation to postfix notation using stack.
1.4 Write a program to implement Tower of
Hanoi problem.
1.5 Identify widely used application which use
stack data structure for implementation of
its important feature.
2. Queue
2.1 Write a program to implement QUEUE
using arrays that performs following
operations (a) INSERT (b) DELETE (c)
DISPLAY
2.2 Write a program to implement Circular
Queue using arrays that performs
following operations. (a) INSERT (b)
DELETE (c) DISPLAY
2.3 Identify widely used application which use
Queue data structure for implementation of
its important feature.
3. Singly linked list
3.1 Write a menu driven program to
implement following operations on the
singly linked list.
(a) Insert a node at the front of the
linked list.
(b) Insert a node at the end of the linked
list.
(c) Insert a node such that linked list is in
ascending order.(according to info.
Field)
Data Structure (3130702) Enrollment No

(d) Delete a first node of the linked list.


(e) Delete a node before specified
position.
(f) Delete a node after specified position.
3.2 Write a program to implement stack using
linked list.
3.3 Write a program to implement queue
using linked list.
4. Doubly linked list
4.1 Write a program to implement following
operations on the doubly linked list.
(a) Insert a node at the front of the linked
list.
(b) Insert a node at the end of the linked
list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified
position.
5. Circular linked list
5.1 Write a program to implement following
operations on the circular linked list.
(a) Insert a node at the end of the linked
list.
(b) Insert a node before specified
position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which
use Linked List for implementation of its
important feature.

6. Tree
6.1 Write a program which create binary
search tree.
6.2 Implement recursive tree traversing
methods in-order, pre-order and post-order
traversal.
6.3 Identify widely used application which use
Tree data structure for implementation of
its important feature.
7. Graph
7.1 Write a program to perform BFS and DFS
on given graph.
Data Structure (3130702) Enrollment No

7.2 Identify widely used application which use


Graph data structure for implementation of
its important feature.
8. Searching
8.1 Write a program to implement Linear
Search.
8.2 Write a program to implement Binary
Search.
8.3 Identify widely used application which
use Searching technique for
implementation of its important feature.
9. Sorting
9.1 Write a program to implement Quick Sort
9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used application which use
Sorting technique for implementation of its
important feature.
10. Hashing and File Structure
10.1 Write a program to create hash table and
handle the collision using linear probing.
10.2 Write a program to demonstrate the file
primitives such as fopen, fclose, fprintf.
10.3 Identify widely used application which
use Hashing technique for implementation
of its important feature.
Total
Data Structure (3130702) 220210132022
Experiment No – 1
AIM : Classification of Data Structure and Stack

1.1 Classify various data structures


1.2 Implement a program for stack that performs following operations using array. (a) PUSH
(b) POP (c) PEEP (d) CHANGE (e) DISPLAY
1.3 Implement a program to convert infix notation to postfix notation using stack.
1.4 Write a program to implement Tower of Hanoi problem.
1.5 Identify widely used application which use stack data structure for implementation of its
important feature.

Date: // Write date of experiment here

Competency and Practical Skills: Logic building and programming

Relevant CO: CO1, CO2, CO5

Objectives: (a) To analyze various data structures


(b) To understand the concepts of stack
(c) To implement various applications of the stack

Equipment/Instruments: Computer System with C/C++ compiler

Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Data Structure

Data structures are a fundamental concept in computer science that enable efficient storage and
manipulation of data. They are used to organize and store data in a manner that allows for optimal
performance of algorithms. The selection of a suitable data structure begins with the choice of an
abstract data type, which defines the operations that can be performed on the data. Well-designed
data structures can perform a wide range of critical operations while using minimal resources such
as execution time and memory space. In essence, data structure introduction refers to the
arrangement of data in a computer's memory in a way that enables rapid access by the processor
for the required calculations.

Stack

A stack is a data structure that follows the last-in first-out (LIFO) principle, meaning that objects
are inserted and removed from the container in a particular order. In pushdown stacks, only two

15
Data Structure (3130702) 220210132022

operations are allowed: pushing an item onto the stack, and popping an item off the top of the
stack. Access to the stack is limited, as elements can only be added and removed from the top.
When an item is pushed onto the stack, it becomes the new top item. Conversely, when an item is
popped off the stack, it is removed from the top.

To illustrate this concept, consider a stack of books. Just as you can only remove the top book,
you can only add a new book to the top of the stack. A stack can also have a limited capacity. If
the stack is already full and there is no space to add a new item, it is said to be in an overflow
state. On the other hand, if the stack is empty and an item is removed, it is in an underflow state,
meaning that no items are present in the stack to be removed.

A stack is an abstract data structure that operates on the LIFO principle, where the last item added
is the first item to be removed. Items can be inserted and deleted at one end called the top,
creating a structure that resembles a closed tube on one side.

 The add operation of the stack is called push operation


 The delete operation is called as pop operation.
 Push operation on a full stack causes stack overflow.
 Pop operation on an empty stack causes stack underflow.
 SP is a pointer, which is used to access the top element of the stack.
 If you push elements that are added at the top of the stack;
 In the same way when we pop the elements, the element at the top of the stack is deleted.

There are two operations applied on stack they are

(1) PUSH
(2) POP

In-fix- to Postfix Conversion:

Procedure to convert from infix expression to postfix expression is as follows:

1. Start scanning the infix expression from left to right.


2. If the symbol scanned is a left parenthesis, push it onto the stack.
3. If the scanned symbol is an operand, place it directly into the postfix expression output.
4. If the symbol scanned is a right parenthesis, continue to pop all items from the stack and
place them into the postfix expression output until a matching left parenthesis is found.
5. If the scanned symbol is an operator, remove all operators from the stack and place them
in the postfix expression output if and only if the precedence of the operator on top of the
stack is greater than or equal to the precedence of the scanned operator. Then push the
scanned operator onto the stack; otherwise, push the scanned operator onto the stack.

16
Data Structure (3130702) 220210132022

1.1 Classify various data

structures Classification of Data

Structures:

Data structures can be classified as

1. Primitive data structure


2. Non-Primitive data structure
(a) Linear data structure
(b) Non-linear data structure

1. Primitive data structures: Primitive data structures are simple data structures
constructed using the standard data types of a computer language. Examples of
primitive data structures include variables, arrays, pointers, structures, unions, and
more. These structures are used to build more complex data structures

2. Non-primitive data structures: Non-primitive data structures are constructed using


primitive data structures and have specific functionality. They can be designed by a
user and are classified into two categories: linear data structures and non-linear data
structures.

(a) Linear data structures

Linear data structures are arranged as a continuous set of data elements in the memory
and can be constructed using array data types. In linear data structures, the adjacency
relationship between data elements is maintained.

Operations applied on linear data structure:

The following list of operations applied on linear data structures

 Add an element
 Delete an element
 Traverse
 Sort the list of elements
 Search for a data element

Examples of linear data structure

 Stack
 Queue
 Tables
 List
 Linked Lists.
17
Data Structure (3130702) 220210132022

(b) Non-linear Data Structure:

Non-linear data structures are not arranged in a continuous manner and include data
structures such as trees and graphs. These structures can be used to represent complex
relationships between data elements.

Operations applied on non-linear data structures:

The following list of operations applied on non-linear data structures.

 Add elements
 Delete elements
 Display the elements
 Sort the list of elements
 Search for a data element

Examples of non-linear data structure

 Tree
 Decision tree
 Graph
 Forest

1.2 Implement a program for stack that performs following operations using array.
(a) PUSH (b) POP (c) PEEP (d) CHANGE (e)

DISPLAY Program:

#include<stdio.h>
#define size 5

struct stack
{
int a[size],top;
int temp[size];
}s;

// PUSH Operation

void push()
{
int value;
printf(" Enter value to be pushed:
"); scanf("%d", &value);
s.top = s.top + 1;
s.a[s.top] = value;
18
Data Structure (3130702) 220210132022
}
// POP Operation

void pop()
{
printf(" Popped element is %d\n", s.a[s.top]);
s.top = s.top - 1;
}

// PEEP Operation

void peep()
{
printf(" The value at top position is : %d\n", s.a[s.top]);
}

// DISPLAY Operation

void display()
{
int i;
printf(" The stack contains:
"); for(i=s.top; i>=0; i--)
{
printf("\t%d", s.a[i]);
}
printf("\n");
}

// CHANGE Operation

void change(int index, int new_element)


{
int i, j=-1;
for(i=s.top; i>index; i--)
{
s.temp[++j] = s.a[s.top--];
}
s.a[s.top] = new_element;
for(i = j; i>-1; i--)
{
s.a[++s.top] = s.temp[j--];
}
}

19
Data Structure (3130702) 220210132022

void main()
{
s.top = -1;
int choice, index,
new_element; do
{
printf("\n STACK IMPLEMENTATION PROGRAM");
printf("\n 1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 0. EXIT\n");
printf("\n Enter your choice:
"); scanf("%d", &choice);
switch(choice)
{
case 1:
if(s.top == size-1)
{
printf("\tSTACK OVERFLOW\n");
}
else
{
push();
}
break
case 2: ;
if(s.top == -1)
{
printf("\tSTACK UNDERFLOW\n");
}
else
{
pop();
}
break
case 3: ;
if(s.top == -1)
{
printf("\tStack is empty.\n");
}
else
{
peep();
}
break
case 4: ;
printf(" Enter index no : ");
scanf("%d",&index);

20
Data Structure (3130702) 220210132022

if(index<0 || index>s.top)
{
printf("\tINVALID INDEX NUMBER\n");
}
else
{
printf(" Enter new element:
"); scanf("%d",
&new_element);
} change(index, new_element);
break
case 5: ;
if(s.top == -1)
{
printf("\t Stack is empty.\n");
}
else
{
display();
}
break
case 0: ;
printf("\tEND OF PROGRAM");
break;
default :
printf("\tINVALID CHOICE\n");
}

} while(choice != 0);

21
Data Structure (3130702) 220210132022
Output:

1.3 Implement a program to convert infix notation to postfix notation using stack.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include
<string.h> #define
MAX 20

char st[MAX];
int top=-1;
void push(char st[], char);
char pop(char st[]);
void InfixtoPostfix(char source[], char
target[]); int getPriority(char);

int main()
{
char infix[100], postfix[100];
printf("\n Enter any infix expression :
"); scanf("%s",infix);
strcpy(postfix, "");
InfixtoPostfix(infix, postfix);
printf("\n The corresponding postfix expression is : ");
puts(postfix);
22
Data Structure (3130702) 220210132022
getch();

23
Data Structure (3130702) 220210132022

return 0;
}

void InfixtoPostfix(char source[], char target[])


{
int i=0,
j=0; char
temp;
strcpy(target, "");
while(source[i]!='\0')
{
if(source[i]=='(')
{
push(st, source[i]);
i++;
}
else if(source[i] == ')')
{
while((top!=-1) && (st[top]!='('))
{
target[j] = pop(st);
j++;
}
if(top==-1)
{
printf("\n INCORRECT EXPRESSION");exit(1);
}
temp = pop(st);//remove left parenthesis
i++;
}
else if(isdigit(source[i]) || isalpha(source[i]))
{
target[j] = source[i];
j++;
i++;
}
else if (source[i] == '+' || source[i] == '-' || source[i] == '*' || source[i] == '/' || source[i] ==
'%')
{
while( (top!=-1) && (st[top]!= '(') && (getPriority(st[top]) >= getPriority(source[i])))
{
target[j] = pop(st);
j++;
}
push(st, source[i]);
i++;
24
Data Structure (3130702) 220210132022
}
els
e
{ printf("\n INCORRECT ELEMENT IN EXPRESSION");exit(1);

}
}
while((top!=-1) && (st[top]!='('))
{
target[j] = pop(st);
j++;
}
target[j]='\0';
}

int getPriority(char op)


{
if(op=='/' || op == '*' ||
op=='%') return 1;
else if(op=='+' || op=='-')
return 0;
}
void push(char st[], char val)
{
if(top==MAX-1)
{
printf("\n STACK OVERFLOW");
}
els
e
{ top++;
st[top]=val;

}
}

char pop(char st[])


{
char val=' ';
if(top==-1)
{

} }
els
e
{

25
Data Structure (3130702) 220210132022
printf("\n
STACK
UNDERFLO
W");

v
a
l
=
s
t
[
t
o
p
]
;

t
o
p
-
-
;

26
Data Structure (3130702) 220210132022

return val;
}

Output:

1.4 Write a program to implement Tower of Hanoi problem.

Program:

#include <stdio.h>

void main()
{
int n;
printf("\n Enter the number of rings: ");
scanf("%d", &n);
move(n,'A', 'C', 'B');
}
void move(int n, char source, char dest, char spare)
{
if (n==1)
printf("\n Move from %c to %c",source,dest);
els
e
{ move(n-1, source, spare, dest);
move(1, source, dest, spare);
move(n-1, spare, dest, source);

}
}

27
Data Structure (3130702) 220210132022
Output:

1.5 Identify widely used application which use stack data structure for implementation of
its important feature.

Stack Applications:

1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.
6. Depth first search uses a stack data structure to find an element from a graph.

Observations:

// Write your observation here

Conclusion:

// Write conclusion here

28
Data Structure (3130702) 220210132022
Quiz:

(1) List various stack operations


(2) Differentiate FIFO and LIFO
(3) Explain infix, prefix and postfix expressions

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

// Write references used by you here

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

29
Data Structure (3130702) 230213132007

Experiment No: 2

AIM : Queue

2.1 Write a program to implement QUEUE using arrays that performs


following operations (a)INSERT (b) DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using arrays that performs
following operations. (a) INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which uses Queue data structure for
implementation of its important feature.

Date: 17/10/23

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of Queue


(b) To analyze different algorithms on Queue
(c) To implement various operations on Queue

Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Queue

A queue is a data structure that follows the First In, First Out (FIFO) principle. It is a special type
of list where items are inserted at the rear and deleted from the front end. Queues can be
compared to real-world scenarios, such as people waiting in line at a bank.

There are various types of Queue in data structure

 Queue
 Circular Queue
 D-Queue
 Priority Queue

13
Data Structure (3130702) 230213132007

2.1 Write a program to implement QUEUE using arrays that performs


following operations. (a)INSERT (b) DELETE (c) DISPLAY

Program:

#include <stdio.h>
#include <stdlib.h>

void Qins(int x);


void Qdel();
void Qdis();

int Q[50], front = -1, rear = -1, N, c;

int main() {
printf("\nEnter choice:\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d", &c);

do {
switch (c) {
case 1:
{
int x;
printf(" Insert in queue: ");
scanf("%d", &x);
Qins(x);
}
break;
case 2:
Qdel();
break;
case 3:
Qdis();
break;
default:
exit(0);
}
printf("\nEnter your choice:\
n"); printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d", &c);
} while (c > 0 && c < 4);
return 0;
14
Data Structure (3130702) 230213132007
}

void Qins(int x) {
if (rear == N - 1) {
printf("Inserted...!!\n");
} else {
if (front == -1) {
front = rear = 0;
} else {
rear = rear + 1;
}
Q[rear] = x;
}
}

void Qdel() {
if (front == -1) {
printf("Deleted...!!\n");
} else {
if (front == rear) {
front = rear = -1;
} else {
front = front + 1;
}
}
}

void Qdis() {
int i;
if (front == -1) {
printf("Displayed..!!\n");
} else {
for (i = front; i <= rear; i++) {
printf("%d\t", Q[i]);
}
printf("\n");
}
}

15
Data Structure (3130702) 230213132007

Output:

2.2 Write a program to implement Circular Queue using arrays that performs
following operations. (a) INSERT (b) DELETE (c) DISPLAY

Program:
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

int front = -1;


int rear = -1;
int q[MAX_SIZE];

// Function to check if the queue is empty


int isEmpty() {
return (front == -1 && rear == -1);
}

// Function to check if the queue is


full int isFull() {
return ((rear + 1) % MAX_SIZE == front);
}

// Function to insert an element into the circular


queue void ins(int x) {
if (isFull()) {
printf("Queue is full!\
n"); return;
}

if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
16
Data Structure (3130702) 230213132007
}

q[rear] = x;
}

// Function to delete an element from the circular queue


int del() {
if (isEmpty()) {
printf("Queue is empty!\
n"); return -1;
}

int deletedItem = q[front];

if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}

return deletedItem;
}

// Function to display the circular


queue void display() {
if (isEmpty()) {
printf("Queue is empty!\
n"); return;
}

int i = front;
do {
printf("%d ", q[i]);
i = (i + 1) % MAX_SIZE;
} while (i != (rear + 1) % MAX_SIZE);

printf("\n");
}

int main() {
int c, x;

while (1) {
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");

printf("Enter your choice:


"); scanf("%d", &c);

switch (c) {
case 1:

17
Data Structure (3130702) 230213132007
printf("Enter value to insert: ");
scanf("%d", &x);
ins(x);
break;
case 2:
x = del();
if (x != -1)
{ printf("Deleted:
%d\n", x);
}
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice!\n");
}
}

return 0;
}
Output:

2.3 Identify widely used application which uses Queue data structure for
implementation of its important feature.
Queues are a versatile data structure used in many widely used applications, including:
• Web servers: to process user requests in order.
• Job schedulers: to manage and execute jobs in order.
• Operating systems: to manage tasks, such as CPU scheduling, disk scheduling, and printing.
• Networking devices: to manage data packets.
• Databases: to manage database transactions.
• Media players: to manage playlists.
• Call centers: to manage customer calls.
• Message brokers: to manage messages between different systems.
18
Data Structure (3130702) 230213132007

Observations:
1. InQueue all deletions (dequeue) are made at the front and all insertions (enqueue) are made at the
rear end.
2. Circular Queue: Circular Queue is just a variation of the linear queue in which front and rear-end are
connected to each other to optimize the space wastage of the Linear queue and make it efficient.

Conclusion:
As the insertion in the queue is from the rear end and in the case of Linear Queue of fixed size insertion is
not possible when rear reaches the end of the queue.
But in the case of Circular Queue, the rear end moves from the last position to the front position
circularly.
Quiz:
(1) Explain concepts of Queue
 A queue is an ordered collection of items where the addition of new items happens at
one end, called the “rear,” and the removal of existing items occurs at the other end,
commonly called the “front.”
(2) Define DQueue
 a double-ended queue (abbreviated to deque) is an abstract data type that generalizes
a queue, for which elements can be added to or removed from either the front (head)
or back (tail).
(3) Differentiate Circular Queue and Priority Queue
 Both circular and priority queues follow queue mechanisms, which are in either a linear
or circular queue fashion. The circular line has the first in, first out functionality,
whereas the priority queue follows the elements with the highest priority to be served
first.

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International

3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.


4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the


students: Rubric-wise marks
obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)
Marks

19
Data Structure (3130702) 230213132007

Experiment No: 3

AIM : Singly linked list

3.1 Write a menu driven program to implement following operations on the singly
linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order. (According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.
3.2 Write a program to implement stack using linked list
3.3 Write a program to implement queue using linked list.

Date: 17-10-23

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of singly linked list


(b) To analyze different algorithms on singly link list
(c) To implement various operations on singly link

list Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Singly link list

A linked list is a type of data structure that stores a collection of non-sequential data items. Unlike
arrays, linked lists are dynamic and their size can be changed during program execution. Each
data item in a linked list has a pointer that holds the memory address of the next data item in the
list. The data items in a linked list may not be stored in consecutive memory locations, but their
pointers make it easy to access them in any order.

A singly linked list, also known as a linear linked list, is a type of linked list in which all nodes
are connected together sequentially. Each node in a singly linked list contains data and a
20
Data Structure (3130702) 230213132007
pointer to

21
Data Structure (3130702) 230213132007
the next node. The last node's pointer is set to null. The limitation of a singly linked list is that it
can only be traversed in one direction, in a forward direction.

Operations on singly linked list

 Insert
- Insert at first position
- Insert at last position
- Insert into ordered list
 Delete
 Traverse list (Print list)
 Copy linked list

3.1 Write a menu driven program to implement following operations on the singly
linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order.(According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void insertAtFront(struct Node** head, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = data;
newNode->next = *head;
*head = newNode;
}

void insertAtEnd(struct Node** head, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL)
{
22
Data Structure (3130702) 230213132007
current = current->next;

23
Data Structure (3130702) 230213132007
}
current->next = newNode;
}
}

void insertInAscendingOrder(struct Node** head, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = data;
newNode->next = NULL;

if (*head == NULL || data < (*head)->data) {


newNode->next = *head;
*head = newNode;
} else if (data > (*head)->data) {
struct Node* current = *head;
while (current->next != NULL && current->next->data < data) {
current = current->next;
}
if (current->next == NULL || current->next->data != data) {
newNode->next = current->next;
current->next = newNode;
} else {
free(newNode);
}
} else {
free(newNode);
}
}

void deleteFirstNode(struct Node** head) {


if (*head != NULL) {
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
}
}

void deleteNodeBeforePosition(struct Node** head, int position)


{ if (*head == NULL || position <= 1) {
return;
}

if (position == 2) {
deleteFirstNode(head);
return;
}

struct Node* current = *head;


for (int i = 1; current != NULL && i < position - 2; i++) {
current = current->next;
}

if (current == NULL || current->next == NULL) {

24
Data Structure (3130702) 230213132007
return;
}

struct Node* temp = current->next;


current->next = current->next-
>next; free(temp);
}

void deleteNodeAfterPosition(struct Node** head, int position) {


if (*head == NULL || position < 1) {
return;
}

struct Node* current = *head;


for (int i = 1; current != NULL && i < position; i++) {
current = current->next;
}

if (current == NULL || current->next == NULL) {


return;
}

struct Node* temp = current->next;


current->next = current->next-
>next; free(temp);
}

void display(struct Node* head) {


struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

void freeLinkedList(struct Node* head)


{ while (head != NULL) {
struct Node* temp = head;
head = head->next;
free(temp);
}
}

int main() {
struct Node* head = NULL;

insertAtFront(&head, 3);
insertAtFront(&head, 2);
insertAtFront(&head, 1);

printf("Linked List after inserting nodes at the front:\n");


display(head);

25
Data Structure (3130702) 230213132007

insertAtEnd(&head, 4);
printf("Linked List after inserting a node at the end:\n");
display(head);

insertInAscendingOrder(&head, 2);
printf("Linked List after inserting a node in ascending order:\n");
display(head);

deleteFirstNode(&head);
printf("Linked List after deleting the first node:\
n"); display(head);

deleteNodeBeforePosition(&head, 2);
printf("Linked List after deleting a node before position 2:\n");
display(head);

deleteNodeAfterPosition(&head, 2);
printf("Linked List after deleting a node after position 2:\n");
display(head);

freeLinkedList(head);

return 0;
}
Output:

3.2 Write a program to implement stack using linked

list Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


26
Data Structure (3130702) 230213132007
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = data;
newNode->next = NULL;
return newNode;
}

void push(struct Node** top, int data) {


struct Node* newNode =
createNode(data); newNode->next = *top;
*top = newNode;
}

int pop(struct Node** top) {


if (*top == NULL) {
printf("Stack is empty.\
n"); return -1;
}
struct Node* temp = *top;
int data = temp->data;
*top = temp->next;
free(temp);
return data;
}

int isEmpty(struct Node* top) {


return top == NULL;
}

void display(struct Node* top) {


if (isEmpty(top)) {
printf("Stack is empty.\
n"); return;
}
printf("Stack elements:
"); while (top != NULL) {
printf("%d ", top->data);
top = top->next;
}
printf("\n");
}

int main() {
struct Node* top = NULL;

push(&top, 1);
push(&top, 2);
push(&top, 3);

display(top);

27
Data Structure (3130702) 230213132007

int popped = pop(&top);


if (popped != -1) {
printf("Popped element: %d\n", popped);
}

display(top);

return 0;
}
Output:

3.3 Write a program to implement queue using linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Queue {
struct Node* front;
struct Node* rear;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = data;
newNode->next = NULL;
return newNode;
}

struct Queue* createQueue() {


struct Queue* queue = (struct Queue*)malloc(sizeof(struct
Queue)); queue->front = NULL;
queue->rear =
NULL; return queue;

28
Data Structure (3130702) 230213132007
}

int isEmpty(struct Queue* queue) {


return (queue->front == NULL);
}

void enqueue(struct Queue* queue, int data) {


struct Node* newNode = createNode(data);
if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}

int dequeue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty.\
n"); return -1;
}
struct Node* temp = queue->front;
int data = temp->data;
queue->front = temp->next;
free(temp);
return data;
}

void display(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty.\
n"); return;
}
printf("Queue elements: ");
struct Node* current = queue->front;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
struct Queue* queue = createQueue();
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);

29
Data Structure (3130702) 230213132007
display(queue);

int dequeued =
dequeue(queue); if (dequeued !
= -1) {
printf("Dequeued element: %d\n", dequeued);
}

display(queue);

return 0;
}
Output:

Observations:

 The program is a well-designed and implemented singly linked list program. It allows users to perform
various operations on a linked list, including inserting and deleting nodes, in a user-friendly and error-
free manner. The program also manages memory efficiently, avoiding memory leaks.

Conclusion:
 The program is well-designed and implements the fundamental concepts of linked lists correctly. It
provides a user-friendly interface and error handling, making it a reliable tool for managing linked
lists

30
Data Structure (3130702) 230213132007

Quiz
:
1. Which are the operations on singly link list?
 INSERTION
DELETION
SEARCH

2. State the limitation of singly link list


 It requires more space as pointers are also stored with information.
 Different amount of time is required to access each element.
 If we have to go to a particular element then we have to go through all those elements that come before
that element.
 we can not traverse it from last & only from the beginning.

3. Compare array and singly link list


Location of linked list nodes is not continuous. Arrays are based on static memory which means the size
of the array is fixed. Linked lists are based on dynamic memory which means the size of the linked list
is dynamic. Memory uses is lesser than linked list because an array only contains data.

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the

students: Rubric-wise marks

obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

31
Data Structure (3130702) 230213132007

Experiment No: 4

AIM : Doubly linked list

4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

Date:

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of doubly linked list


(b) To analyze different algorithms on doubly link list
(c) To implement various operations on doubly link list

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Doubly linked list

A doubly linked list is a data structure where each node contains data and two pointers - one to
point to the previous node (LPTR) and another to point to the next node (RPTR). The main
advantage of a doubly linked list is that we can traverse it in any direction, either forward or
backward. Another advantage is that we can delete a node with ease since we have pointers to
both the previous and next nodes. In contrast, a node on a singly linked list cannot be removed
unless we have a pointer to its predecessor. However, the drawback of a doubly linked list is that
it requires more memory than a singly linked list since we need an extra pointer to point to the
previous node. In the image, L and R denote the leftmost and rightmost nodes in the list,
respectively. The left link of the L node and the right link of the R node are both NULL,
indicating the end of the list for each direction.

Operations on doubly linked list

 Insert
32
Data Structure (3130702) 230213132007
- Insert at first position
- Insert at last position
- Insert into ordered list
 Delete
 Traverse list (Print list)
 Copy linked list

4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

(a) Insert a node at the front of the linked list.

Program:
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
struct Node *prev;
};

void insertStart (struct Node **head, int data)


{

struct Node *newNode = (struct Node *) malloc (sizeof (struct

Node)); newNode->data = data;


newNode->next = *head;
newNode->prev =
NULL;

if (*head != NULL)
(*head)->prev = newNode;
// *head->prev = newNode; would not work it has (*head) must be used

//changing the new head to this freshly entered node


*head = newNode;
}

// function to print the doubly linked


list void display (struct Node *node)
{
struct Node *end;
printf ("Doubly Linked list : ");

33
Data Structure (3130702) 230213132007
while (node != NULL)

34
Data Structure (3130702) 230213132007
{
printf (" %d ", node->data);
end = node;
node = node->next;
}

int main ()
{
struct Node *head = NULL;

insertStart (&head, 12);


insertStart (&head, 16);
insertStart (&head, 20);

display (head);
return 0;
}

Output:

(b) Insert a node at the end of the linked list.

Program:
#include <stdio.h>

//Represent a node of the doubly linked

list struct node{


int data;
struct node *previous;
struct node *next;
};

//Represent the head and tail of the doubly linked


list struct node *head, *tail = NULL;

//addAtEnd() will add a node to the end of the


list void addAtEnd(int data) {
35
Data Structure (3130702) 230213132007
//Create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct
node)); newNode->data = data;

//If list is empty


if(head == NULL)
{
//Both head and tail will point to
newNode head = tail = newNode;
//head's previous will point to
NULL head->previous = NULL;
//tail's next will point to NULL, as it is the last node of the
list tail->next = NULL;
}
//Add newNode as new tail of the
list else {
//newNode will be added after tail such that tail's next will point to
newNode tail->next = newNode;
//newNode's previous will point to
tail newNode->previous = tail;
//newNode will become new
tail tail = newNode;
//As it is last node, tail's next will point to
NULL tail->next = NULL;
}
}

//display() will print out the nodes of the


list void display() {
//Node current will point to head
struct node *current = head;
if(head == NULL) {
printf("List is empty\n");
return;
}
printf("Adding a node to the end of the list: \
n"); while(current != NULL) {
//Prints each node by incrementing
pointer. printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main()
{
//Adding 1 to the
list addAtEnd(1);
display();
//Adding 2 to the
list addAtEnd(2);
display();
//Adding 3 to the list
36
Data Structure (3130702) 230213132007
addAtEnd(3);
display();
//Adding 4 to the
list addAtEnd(4);
display();
//Adding 5 to the
list addAtEnd(5);
display();

return 0;
}
Output:

(c) Delete a last node of the linked list.

Program:
#include <stdio.h>
#include <stdlib.h>

//node structure
struct Node {
int data;
struct Node* next;
struct Node* prev;
};

//Add new element at the end of the list


void push_back(struct Node** head_ref, int newElement)
{ struct Node *newNode, *temp;
newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = newElement;
newNode->next = NULL;
newNode->prev =
NULL; if(*head_ref ==
NULL) {
*head_ref = newNode;
} else {
temp = *head_ref;
while(temp->next != NULL)
{ temp = temp->next;

37
Data Structure (3130702) 230213132007
}

38
Data Structure (3130702) 230213132007
temp->next = newNode;
newNode->prev =
temp;
}
}

//Delete last node of the list


void pop_back(struct Node** head_ref) {
if(*head_ref != NULL) {
if((*head_ref)->next == NULL) {
*head_ref = NULL;
} else {
struct Node* temp = *head_ref;
while(temp->next->next !=
NULL) temp = temp->next;
struct Node* lastNode = temp-
>next; temp->next = NULL;
free(lastNode);
}
}
}

//display the content of the list


void PrintList(struct Node* head_ref)
{ struct Node* temp = head_ref;
if(head_ref != NULL) {
printf("The list contains: ");
while (temp != NULL) {
printf("%i ",temp->data);
temp = temp->next;
}
printf("\n");
} else {
printf("The list is empty.\n");
}
}

// test the code


int main() {
struct Node* MyList = NULL;

//Add four elements in the


list. push_back(&MyList, 10);
push_back(&MyList, 20);
push_back(&MyList, 30);
push_back(&MyList, 40);
PrintList(MyList);

//Delete the last node


pop_back(&MyList);
PrintList(MyList);

return 0;
39
Data Structure (3130702) 230213132007
}

Output:

(d) Delete a node before specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define a node structure for the doubly linked


list struct Node {
int data;
struct Node*
prev; struct
Node* next;
};

// Function to delete a node before a specified position


void deleteNodeBeforePosition(struct Node** head, int position) {
if (*head == NULL || position <= 1) {
// Invalid position or empty
list return;
}

struct Node* current =


*head; int count = 1;

// Traverse to the node before the specified position


while (count < position - 1 && current->next != NULL)
{ current = current->next;
count++;
}

if (current->prev != NULL) {
// Node to be deleted is not the first node

// Adjust pointers to skip the node to be


deleted current->prev->next = current->next;

if (current->next != NULL) {
current->next->prev = current->prev;
40
Data Structure (3130702) 230213132007
}

// Free the memory of the node to be


deleted free(current);
} else {
// Node to be deleted is the first node
// Update head to skip the first node
*head = current->next;

if (current->next != NULL) {
current->next->prev =
NULL;
}

// Free the memory of the node to be


deleted free(current);
}
}

// Function to print the doubly linked


list void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}

// Function to add a new node at the end of the doubly linked


list void append(struct Node** head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); struct Node* last = *head;

newNode->data =
newData; newNode->next
= NULL;

if (*head == NULL) {
newNode->prev =
NULL;
*head =
newNode; return;
}

while (last->next != NULL) {


last = last->next;
}

last->next = newNode;
newNode->prev =
last;
}

// Example
41
Data Structure (3130702) 230213132007
usage int main()
{
struct Node* head = NULL;

// Appending nodes to the doubly linked list

42
Data Structure (3130702) 230213132007
append(&head, 1);
append(&head, 2);
append(&head, 3);
append(&head, 4);
append(&head, 5);

printf("Original Doubly Linked List:


"); printList(head);

int positionToDeleteBefore = 3;
deleteNodeBeforePosition(&head, positionToDeleteBefore);

printf("Doubly Linked List after deleting before position %d: ", positionToDeleteBefore);
printList(head);

return 0;
}
Output:

43
Data Structure (3130702) 230213132007

Observations:
The program requires careful management of pointers for linking nodes during insertions and deletions in a
doubly linked list.
Conclusion:
Addressing edge cases, implementing proper memory management, and ensuring code readability contribute
to a robust program for manipulating doubly linked lists with specified operations.
Quiz:
(1) Explain structure of a node of doubly link list
 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 three fields: two
link fields (references to the previous and to the next node in the sequence of nodes)
and
one data field.

(2) Which is the main advantage of doubly link list?


 It allows traversing in both forward and backward directions because of the next
and previous pointers

(3) What is the drawback of doubly link list?


 It uses extra memory when compared to the array and singly linked list. Since
elements in memory are stored randomly, therefore the elements are accessed
sequentially no direct access is allowed. Traversing a doubly linked list can be
slower than traversing a singly linked

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni, Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the

students: Rubric-wise marks

obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

44
Data Structure (3130702) 230213132007

Experiment No: 5

AIM : Circular linked list

5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which uses linked list for implementation of its
important feature.

Date:
Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of circular linked list


(b) To analyze different algorithms on circular link list
(c) To implement various operations on circular link

list Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Circular linked list

A circular linked list is similar to a singly linked list, except that the last node points to the first
node, creating a circular arrangement of nodes. Unlike a singly linked list, it does not contain null
pointers. Traversal can only be done in one direction, i.e., the forward direction. The biggest
advantage of a circular linked list is that it saves time when we want to go from the last node to
the first node because it directly points to the first node. A good example of an application where
a circular linked list can be used is a time-sharing problem that can be solved by the operating
system.

Operations on circular linked list

 Insert
- Insert at first position

45
Data Structure (3130702) 230213132007
- Insert at last position
- Insert into ordered list
 Delete
 Traverse list (Print list)
5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.

(a) Insert a node at the end of the linked list.

Program:

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
};

void insertLast (struct Node **head, int data)


{
struct Node *newNode = (struct Node *) malloc (sizeof (struct
Node)); newNode->data = data;

// if its the first node being


entered if (*head == NULL)
{
*head = newNode;
(*head)->next =
*head; return;
}

// if LL already as >=1 node


struct Node *curr = *head;

// traverse till last node in


LL while (curr->next !=
*head)
{
curr = curr->next;
}

// assign LL's current last node's next as this new


node curr->next = newNode;

// assign this new node's next as current head of


LL newNode->next = *head;

46
Data Structure (3130702) 230213132007
}

47
Data Structure (3130702) 230213132007

void display (struct Node *head)


{
// if there are no node in LL
if (head == NULL)
return;

struct Node *temp = head;

//need to take care of circular structure of


LL do
{
printf ("%d ", temp->data);
temp = temp->next;

}
while (temp !=
head); printf ("\n");
}

int main ()
{

struct Node *head = NULL;

printf("Linked List: ");


insertLast (&head, 0);
insertLast (&head, 10);
insertLast (&head, 20);
insertLast (&head, 30);
insertLast (&head, 40);
display (head);

return 0;
}

Output:

48
Data Structure (3130702) 230213132007

(b) Insert a node before specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define a structure for a node in the circular linked list


struct Node {
int data;
struct Node* next;
};

// Function to insert a node before a specified position in a circular linked list


void insertBeforePosition(struct Node** head, int position, int newData) {
// Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->data = newData;

// If the list is empty, make the new node the only node and point to itself
if (*head == NULL) {
newNode->next = newNode;
*head =
newNode; return;
}

// Traverse the list to find the node before the specified


position struct Node* temp = *head;
for (int i = 1; i < position - 1; i++)
{ temp = temp->next;
}

// Insert the new node before the specified


position newNode->next = temp->next;
temp->next = newNode;
}

// Function to print the circular linked


list void printList(struct Node* head) {
if (head == NULL) {
printf("Circular linked list is empty.\n");
return;
}

struct Node* current =


head; do {
printf("%d -> ", current->data);
current = current->next;
} while (current != head);

49
Data Structure (3130702) 230213132007
printf("(head)\n");
}

// Driver program to test the


functions int main() {
struct Node* head = NULL;

// Insert nodes into the circular linked


list insertBeforePosition(&head, 1, 10);
insertBeforePosition(&head, 2, 20);
insertBeforePosition(&head, 3, 30);
insertBeforePosition(&head, 4, 40);

// Print the circular linked list


printf("Original Circular Linked List:
"); printList(head);

// Insert a node before position 2


insertBeforePosition(&head, 2, 25);

// Print the modified circular linked list printf("\


nCircular Linked List after insertion: ");
printList(head);

return 0;
}
Output:

(c) Delete a first node of the linked list.

Program:

#include<stdio.h>
#include<stdlib.h>
// structure for Circular Linked
List struct Node
{
int data;
struct Node *next;
};

void deleteBegin(struct Node **head)


{
50
Data Structure (3130702) 230213132007

struct Node *tempNode = *head;

// if there are no nodes in Linked List can't


delete if (*head == NULL)
{
printf ("Linked List Empty, nothing to
delete"); return;
}

// if only 1 node in CLL


if (tempNode->next == *head)
{
*head =
NULL; return;
}

struct Node *curr = *head;

// traverse till last node in


CLL while (curr->next !=
*head) curr = curr->next;

// assign last node's next to 2nd node in


CLL curr->next = (*head)->next;

// move head to next node


*head = (*head)-
>next; free
(tempNode);
}

void insert (struct Node **head, int data)


{
struct Node *newNode = (struct Node *) malloc (sizeof (struct
Node)); newNode->data = data;

if (*head == NULL)
{
*head = newNode;
(*head)->next =
*head; return;
}

struct Node *curr = *head;

while (curr->next != *head)


{
curr = curr->next;
}

curr->next = newNode;
newNode->next =
*head;
51
Data Structure (3130702) 230213132007
*head = newNode;

52
Data Structure (3130702) 230213132007
}

void display (struct Node *head)


{
// if there are no node in
CLL if (head == NULL)
return;

struct Node *temp = head;

//need to take care of circular structure of


CLL do
{
printf ("%d ", temp->data);
temp = temp->next;

}
while (temp !=
head); printf ("\n");
}

int main ()
{

// first node will be null at


creation struct Node *head =
NULL;

insert (&head, 10);


insert (&head, 11);
insert (&head, 12);
insert (&head, 13);
insert (&head, 14);
insert (&head, 15);
insert (&head, 16);

display (head);

deleteBegin(&head);
display (head);

return 0;
}

Output:

53
Data Structure (3130702) 230213132007

(d) Delete a node after specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node *next;
} Node;

Node *createNode(int data) {


Node *newNode = (Node
*)malloc(sizeof(Node)); newNode->data = data;
newNode->next =
NULL; return newNode;
}

Node *insertNodeAtEnd(Node *head, int data) {


if (head == NULL) {
head =
createNode(data); head-
>next = head; return
head;
}

Node *temp = head;


while (temp->next != head) {
temp = temp->next;
}

Node *newNode =
createNode(data); temp->next =
newNode;
newNode->next =
head; return head;
}

Node *deleteNodeAfterPosition(Node *head, int position) {


if (head == NULL || position < 0) {
return head;
}

Node *prev =
NULL; Node *curr =
head; int count = 0;

while (count <= position) {


prev = curr;
curr = curr-
54
Data Structure (3130702) 230213132007
>next; count++;
}

55
Data Structure (3130702) 230213132007

if (curr == head) {
prev->next = head-
>next; free(head);
head = prev->next;
} else if (curr == NULL)
{ prev->next = head;
} else {
prev->next = curr-
>next; free(curr);
}

return head;
}

void printCircularLinkedList(Node *head)


{ if (head == NULL) {
printf("Circular linked list is empty\
n"); return;
}

Node *temp =
head; do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp !=
head); printf("\n");
}

int main() {
Node *head = NULL;

// Insert nodes into the circular linked


list head = insertNodeAtEnd(head, 10);
head = insertNodeAtEnd(head,
20); head =
insertNodeAtEnd(head, 30);

printf("Original circular linked list:


"); printCircularLinkedList(head);

// Delete the node after the second


position head =
deleteNodeAfterPosition(head, 2);

printf("Circular linked list after deletion:


"); printCircularLinkedList(head);

return 0;
}

56
Data Structure (3130702) 230213132007

Output:

5.2 Identify widely used application which uses linked list for implementation of its
important feature.
 Image viewer – Previous and next images are linked and can be accessed by the next and previous
buttons. Previous and next page in a web browser – We can access the previous and next URL searched in
a web browser by pressing the back and next buttons since they are linked as a linked list.

Observations:

1. Insertions: The implemented methods ensure nodes are added seamlessly at the end or before
a specified position, maintaining the circular structure without disruptions.
2. Deletions: Deletion operations effectively adjust pointers, preserving the circular nature of the
linked list, indicating robust handling of node removal.

Conclusion:
 The implemented circular linked list operations exhibit robust functionality, preserving the
circular structure during insertions and deletions.

Quiz:

(1) What are disadvantages of circular link list?


 Circular lists are complex as compared to singly linked lists.
 Reverse of circular list is a complex as compared to singly or doubly lists.
 If not handled carefully, then the code may go in an infinite loop.
 Harder to find the end of the list and loop control.

(2) Differentiate Circular link list and Queue?


 The major difference between circular linked list and circular queue/circular buffer/ring
buffer is that: In a circular linked list the next pointer of the last node points to the head
(of the linked list)
(3) Which are the operations on circular link list?
 Insertion operation.
 Deletion operation.
 Traversal operation

57
Data Structure (3130702) 230213132007

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms
References used by the

students: Rubric-wise marks

obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

58
Data Structure (3130702) 230213132007

Experiment No: 6

AIM : Tree

6.1 Write a program which create binary search tree.


6.2 Implement recursive tree traversing methods in-order, pre-order and post-order
traversal.
6.3 Identify widely used applications which use Tree data structure for
implementation of its important feature.

Date:

Competency and Practical Skills: Logic building and programming

Relevant CO: CO3, CO5

Objectives: (a) To understand the concepts of Tree


(b) To analyze different algorithms on Tree
(c) To implement various operations on Tree

Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Binary Search Tree

A binary search tree is a binary tree in which each node possessed a key that satisfy the
following conditions

1. All key (if any) in the left sub tree of the root precedes the key in the root.
2. The key in the root precedes all key (if any) in the right sub tree.
3. The left and right sub tree sub trees of the root are again search trees.

Operations on tree

The most common operations performed on tree structure are that of traversal. This is a procedure
by which each node in the tree is processed exactly once in a systematic manner.

There are three ways of traversing a binary tree.

1. Pre-order Traversal
59
Data Structure (3130702) 230213132007
2. In-order Traversal
3. Post-order Traversal
Pre-order

 Pre-order traversal of a binary tree is defined as follow


 Process the root node
 Traverse the left sub tree in pre-order
 Traverse the right sub tree in pre-order
 If particular sub tree is empty (i.e., node has no left or right descendant) the traversal is
performed by doing nothing, In other words, a null sub tree is considered to be fully
traversed when it is encountered.

In-order

 The In-order traversal of a binary tree is given by following steps,


 Traverse the left sub tree in In-order
 Process the root node
 Traverse the right sub tree in In-order

Post-order

 The post-order traversal is given by


 Traverse the left sub tree in post-order
 Traverse the right sub tree in post-order
 Process the root node

6.1 Write a program which create binary search tree.

Program:
#include <stdio.h>
#include <stdlib.h>

// Define a structure for a tree node


struct TreeNode {
int key;
struct TreeNode* left;
struct TreeNode*
right;
};

// Function to create a new node with the given


key struct TreeNode* createNode(int key) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode)); newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to insert a key into the BST


60
Data Structure (3130702) 230213132007
struct TreeNode* insert(struct TreeNode* root, int key) {

61
Data Structure (3130702) 230213132007
// If the tree is empty, create a new node and return
it if (root == NULL) {
return createNode(key);
}

// Otherwise, recur down the tree


if (key < root->key) {
root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}

// Return the (unchanged) node


pointer return root;
}

// Function to perform in-order traversal of the BST


void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->key);
inorderTraversal(root->right);
}
}

// Example
usage int main()
{
struct TreeNode* root = NULL;

// Insert elements into the


BST root = insert(root, 5);
insert(root, 3);
insert(root, 7);
insert(root, 2);
insert(root, 4);
insert(root, 6);
insert(root, 8);

// Print the in-order traversal of the


BST printf("Inorder Traversal: ");
inorderTraversal(root);

return 0;
}
Output:

62
Data Structure (3130702) 230213132007

6.2 Implement recursive tree traversing methods in-order, preorder and post-order
traversal.

Program:
#include <stdio.h>
#include <stdlib.h>

// Define a structure for a tree node


struct TreeNode {
int key;
struct TreeNode* left;
struct TreeNode*
right;
};

// Function to create a new node with the given


key struct TreeNode* createNode(int key) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function for in-order traversal


void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->key);
inorderTraversal(root->right);
}
}

// Function for pre-order traversal


void preorderTraversal(struct TreeNode* root) {
if (root != NULL) {
printf("%d ", root->key);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

// Function for post-order traversal


void postorderTraversal(struct TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->key);
}
}

63
Data Structure (3130702) 230213132007
// Example usage

64
Data Structure (3130702) 230213132007
int main() {
struct TreeNode* root =
createNode(1); root->left =
createNode(2);
root->right = createNode(3);
root->left->left =
createNode(4);
root->left->right = createNode(5);

printf("In-order Traversal:
"); inorderTraversal(root);
printf("\n");

printf("Pre-order Traversal:
"); preorderTraversal(root);
printf("\n");

printf("Post-order Traversal:
"); postorderTraversal(root);
printf("\n");

return 0;
}

Output:

65
Data Structure (3130702) 230213132007

6.3 Identify widely used applications which use Tree data structure for
implementation of its important feature.
File Systems:
File systems often use tree structures to represent the hierarchy of directories and files. Each directory is a
node in the tree, and files are the leaves.

Database Systems:
In database systems, trees are used for indexing and searching. B-trees and B+ trees are common structures
for indexing in databases, allowing for efficient search and retrieval operations.

XML and HTML Parsing:


XML and HTML documents are often represented as tree structures. Parsing these documents involves
creating a tree representation where each node corresponds to an element or tag.

Compiler Design:
Abstract Syntax Trees (AST) are used in compiler design to represent the hierarchical structure of source
code. ASTs help in the analysis and optimization of code during compilation.

Network Routing Algorithms:


Tree structures are employed in routing algorithms, such as spanning trees in network protocols like
Spanning Tree Protocol (STP) used in Ethernet networks.

Graphical User Interfaces (GUI):


GUI frameworks often use tree structures to represent the hierarchy of UI components. This is especially
true in widget toolkits where components like windows, panels, and buttons are organized in a tree.

Operating Systems:
Process scheduling and resource allocation in operating systems can be modeled using tree structures.
Process Control Block (PCB) trees are an example, where each process is a node in the tree.

Artificial Intelligence and Decision Trees:


Decision trees are used in machine learning and AI for decision-making processes. They are employed in
classification algorithms and are useful for representing complex decision logic.

Observations:
 Tree Traversal: Recursive methods successfully implement in-order, pre-order, and post-order
traversals.
 Applications: Widely used in databases, file systems, networking, and more.

Conclusion:
 BST Creation: Efficiently creates a Binary Search Tree (BST).

Quiz:

(1) Define binary search tree


 A Binary Search Tree (BST) is a binary tree where each node's key is greater than all keys in its left
sub tree and less than all keys in its right sub tree, facilitating efficient search, insertion, and
deletion operations.

66
Data Structure (3130702) 230213132007

(2) Explain pre-order, in-order and post order traversal techniques


 Pre-order Traversal: Visits the current node before its children.
 In-order Traversal: Visits the left child, then the current node, and finally the right child, resulting
in a sorted order for BSTs.
 Post-order Traversal: Visits the children before the current node, useful for tasks like deleting nodes.
(3) Which are the applications of binary search tree?
 Database Indexing: Efficient for searching and indexing operations in databases.
 File Systems: Representing hierarchical file structures for quick retrieval.
 Symbol Tables: Utilized in compilers and interpreters for efficient symbol lookup.
 Network Routing: Used in network protocols to determine optimal routes.
 Dynamic Order Statistics: Finding the k-th smallest or largest element in dynamic sets.
 Binary Heap: Building blocks for implementing priority queues.
 Game Trees: Applied in artificial intelligence for decision-making processes.
 Balancing Data: Ensuring balanced tree structures for optimal performance.

Suggested Reference:

3. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul


G. Sorenson Publisher-Tata McGraw Hill.
4. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
5. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
6. http://www.geeksforgeeks.org/data-structures/
7. http://www.coursera.org/specializations/data-structures-algorithms

References used by the

students:

67
Data Structure (3130702) 230213132007

Experiment No: 7

AIM : Graph

7.1 Write a program to perform BFS and DFS on given graph.


7.2 Identify widely used applications which use graphs data structure for
implementation of its important feature.

Date: // Write date of experiment here

Competency and Practical Skills: Logic building and programming

Relevant CO: CO3, CO5

Objectives: (a) To understand the concepts of graphs


(b) To analyze different algorithms on graphs
(c) To implement various operations on graphs

Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Graph:

A graph G can be defined as a non-empty set of vertices or nodes (V) and a set of edges (E) that
represents the relationship or connection between those nodes. The edges can be defined as a
mapping from E to pairs of elements of V. A graph can be represented as G = (V, E), where V
represents the set of nodes and E represents the set of edges. Each edge of the graph G can be
associated with a pair of nodes of the graph. If an edge X belongs to E and is associated with a
pair of nodes (u, v), where u and v belong to V, then we say that edge X connects node u and node
v.

Depth First Search (DFS):

DFS is a graph traversal algorithm that is similar to the preorder traversal of a tree. The traversal
can start from any vertex vi of the graph. Initially, the vertex vi is visited, and then all the adjacent
vertices to vi are traversed recursively using DFS. As a graph can have cycles, we need to avoid
revisiting a node. To achieve this, when a vertex V is visited, it is marked as visited and should
not be selected for traversal again.

68
Data Structure (3130702) 230213132007

Breadth First Search (BFS)

 Breadth First Search (BFS) starts from a vertex v0 and marks it as visited. Then, all the
vertices adjacent to v0 are visited next.
 Let the vertices adjacent to v0 be v1, v2, v3, and v4. These vertices are marked as visited.
 All unvisited vertices adjacent to v1, v2, v3, and v4 are visited next.
 The above process continues until all vertices are visited.
 The algorithm for BFS maintains a list of vertices that have been visited but not explored
for adjacent vertices. This list is stored in a queue.
 The queue initially contains the starting vertex.
 In each iteration, a vertex is removed from the queue, and its adjacent vertices, which
have not been visited yet, are added to the queue.
 The algorithm terminates when the queue becomes empty.

7.1 Write a program to perform BFS and DFS on given graph.

Program:

// Write code of your program here

Output:

// Write output of your program here

7.2 Identify widely used applications which use graphs data structure for
implementation of its important feature.

// Write relevant contents here

Observations:

// Write your observation here

Conclusion:

// Write conclusion here

Quiz:

(1) Define Directed Acyclic Graph (DAG).


(2) Differentiate DFS and BFS.
(3) State the applications of graph.

69
Data Structure (3130702) 230213132007

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

// Write references used by you here

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)
Marks

70
Data Structure (3130702) 230213132007

Experiment No: 8

AIM : Searching

8.1 Write a program to implement Linear Search.


8.2 Write a program to implement Binary Search.
8.3 Identify widely used applications which use Searching technique for implementation
of its important feature.

Date: // Write date of experiment here

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Searching


(b) To analyze different algorithms on Searching
(c) To implement various operations on Searching

Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Linear/Sequential Search

 Linear search, also known as sequential search, is a technique used in computer science to
find a specific value in a list by sequentially checking each of its elements one at a time
until the desired one is found.
 It is the simplest search algorithm and a form of brute-force search. Its worst-case cost is
proportional to the number of elements in the list.

Binary Search

 If we have an array that is sorted, we can use a much more efficient algorithm called
Binary Search.
 In Binary Search, we divide the array into two equal halves and compare the middle
element with the search element.
 If the middle element is equal to the search element, we have found the element and return
its index; otherwise, if the middle element is less than the search element, we look at the

71
Data Structure (3130702) 230213132007
right part of the array, and if the middle element is greater than the search element,

we look at the left part of the array.

8.1 Write a program to implement Linear Search.

Program:

// Write code of your program here

Output:

// Write output of your program here

8.2 Write a program to implement Binary Search.

Program:

// Write code of your program here

Output:

// Write output of your program here

8.3 Identify widely used applications which use Searching technique for implementation
of its important feature.

// Write relevant contents here

Observations:

// Write your observation here

Conclusion:

// Write conclusion here

Quiz:

(1) List out searching algorithms


(2) Differentiate sequential search and binary search
(3) Which are the applications of binary search algorithm?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul


G. Sorenson Publisher-Tata McGraw Hill.
72
Data Structure (3130702) 230213132007
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

// Write references used by you here

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)
Marks

73
Data Structure (3130702) 230213132007

Experiment No: 9

AIM : Sorting

9.1 Write a program to implement Quick Sort


9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used applications which use Sorting technique for
implementation of its important feature.

Date: // Write date of experiment here

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Sorting


(b) To analyze different algorithms on Sorting
(c) To implement various operations on Sorting

Equipment/Instruments: Computer System with turbo C/C+

+ Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Bubble sort

Bubble sort, also known as sinking sort, is a comparison-based sorting algorithm. It works by
repeatedly scanning through the list to be sorted, comparing adjacent elements and swapping them
if they are not in the correct order. In each pass through the list, the largest element bubbles up to
the top. The algorithm repeats these processes until no more swaps are needed, indicating that the
list is sorted. Although it is simple to understand and implement, bubble sort has a worst-case and
average time complexity of O(n^2), making it too slow for large inputs. Insertion sort is a more
efficient alternative for small lists.

Merge Sort

 The merge sort algorithm is based on the classical divide-and-conquer paradigm. It


operates as follows:

74
Data Structure (3130702) 230213132007
 DIVIDE: Partition the n-element sequence to be sorted into two sub sequences of
n/2 elements each.
 CONQUER: Sort the two sub sequences recursively using the merge sort.

 COMBINE: Merge the two sorted sub sequences of size n/2 each to produce the
sorted sequence consisting of n elements.

Quick Sort

Quicksort is currently the fastest known sorting algorithm and often the most practical choice for
sorting, with an average expected running time of O(n log(n)). Its operation consists of the
following steps:
 Pick an element from the array, known as a pivot.
 Reorder the array so that all elements with values less than the pivot are placed before it,
while all elements with values greater than the pivot come after it (elements with equal
values can go either way). This operation is called partitioning, and at the end of it, the
pivot is in its final position.
 Recursively apply the above steps to the sub-arrays of elements with smaller and greater
values, respectively. Quicksort, like merge sort, is a divide-and-conquer recursive
algorithm.
 The basic divide-and-conquer process for sorting a sub array is given in the following
three easy steps:
 Divide
 Conquer
 Combine

9.1 Write a program to implement Quick

Sort Program:

// Write code of your program here

Output:

// Write output of your program here

9.2 Write a program to implement Merge

Sort Program:

// Write code of your program here

Output:

// Write output of your program here

75
Data Structure (3130702) 230213132007

9.3 Write a program to implement Bubble

Sort Program:

// Write code of your program here

Output:

// Write output of your program here

9.4 Identify widely used applications which use Sorting technique for
implementation of its important feature.

// Write relevant contents here

Observations:

// Write your observation here

Conclusion:

// Write conclusion here

Quiz:

(1) Define sorting


(2) What is divide-and-conquer strategy for sorting?
(3) Which is the best suitable sorting algorithm as per its execution time?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

// Write references used by you here

76
Data Structure (3130702) 230213132007

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

77
Data Structure (3130702) 230213132007

Experiment No: 10

AIM : Hashing and File Structure

10.1 Write a program to create hash table and handle the collision using linear probing.
10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.
10.3 Identify widely used applications which use Hashing technique for implementation
of its important feature.

Date: // Write date of experiment here

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Hashing techniques


(b) To implement various file operations

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

 Operate computer system carefully and responsibly.


 Use required lab resources cautiously

Theory:

Hashing

Hashing is a method used to map a large number of data items to a smaller table by utilizing a
hashing function. This technique transforms a range of key values into a range of indexes of an
array.There are two different forms of hashing.

1. Open hashing or external hashing: Open or external hashing, allows records to be


stored in unlimited space (could be a hard disk). It places no limitation on the size of the
tables.
2. Close hashing or internal hashing: Closed or internal hashing, uses a fixed space for
storage and thus limits the size of hash table.

Hashing Functions

Characteristics of a Good Hash Function


 A good hash function avoids collisions.
 A good hash function tends to spread keys evenly in the array.
78
Data Structure (3130702) 230213132007
 A good hash function is easy to compute.

Different hashing functions

1. Division-Method
2. Folding Method
3. Algebraic Coding
4. Multiplicative Hashing
5. Digit Analysis
6. Mid-square Methods
7. Length Dependent Method

Collision Resolution Strategies

 Collision resolution is the main problem in hashing.


 If the element to be inserted is mapped to the same location, where an element is already
inserted then we have a collision and it must be resolved.
 There are several strategies for collision resolution. The most commonly used are :
1. Separate chaining - used with open hashing
2. Open addressing - used with closed hashing

File

In computing, a file is a group of records, where each record comprises one or more fields that
have the same sequence. Typically, each field has a predetermined length.

Different file organizations

1. Sequential files
2. Direct files
3. Index files
4. Indexed Sequential files
5. Relative files

Primitive Operations on a File

1. Creation
2. Insertion
3. Deletion
4. Updation
5. Reading
6. Searching

79
Data Structure (3130702) 230213132007

10.1 Write a program to create hash table and handle the collision using linear probing.

Program:

// Write code of your program here

Output:

// Write output of your program here

10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.

Program:

// Write code of your program here

Output:

// Write output of your program here

10.3 Identify widely used applications which use Hashing technique for implementation
of its important feature.

// Write relevant contents here

Observations:

// Write your observation here

Conclusion:

// Write conclusion here

Quiz:

(1) What is internal hashing and external hashing?


(2) Explain linear probing.
(3) Which are primitive operations on file?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
80
Data Structure (3130702) 230213132007
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

// Write references used by you here

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

81

You might also like