0% found this document useful (0 votes)
42 views38 pages

DS Lab Manual CD 303

Uploaded by

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

DS Lab Manual CD 303

Uploaded by

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

A Practical File

of
“Data Structures (CD 303)”

Data Science (CSE)

Submitted by

Name:

Enrolment No.:

Semester:

Session:

Submitted to:

Prof. Pankaj Pali


Department of Computer Science and Engineering

Baderia Global Institute of Engineering and Management, JABALPUR (M.P.)


Global Square, Patan Bypass, Raigwan, Jabalpur, M.P., 482002
Data Structure Lab Manual

Contents

 Vission & Mission of the Institute

 Vission & Mission of the Department

 Program Educational Objectives

 Program Outcomes

 Course Outcomes

 Laboratory Regulations & Safety Rules

 List of Experiment
Vission & Mission of the Institute

Vission of the Institute


Transforming life by providing professional education with
execellence.

Mission of the Institute


1. Quality Education: Providing Education with quality and shaping
up Technocrats and budding managers with a foucs on adapting
to changing technologies.
2. Focused Research & Innovation: Focussing on Research and
Development and fostering Innovation among the academic
community of the Institution.
3. People Focussed: Accountable and committed to institutional
operations for effective functioning by Faculty members, Staff
and Students.
4. Holistic Learning: Focus on conceptual learning with practical
experience and experimential learning with strong Industial
connections and collaborations.
5. Service to Society: Providing Technical and Managerial services
to society for betterment of their quality of life with best of the
skills, compassion and empathy.
Vission & Mission of the Department

Vission of the Department


Cultivating leaders in Data Science who drive innovation and informed
decision-making through the power of data analytics and scientific discovery.

Mission of the Department


The department strives to:

1. Foster a student-centric learning environment that equips


graduates with cutting-edge knoledge and skills in data science,
analytics, and related technologies.
2. Develop professionals who can apply data-driven approaches to
solve complex problems across diverse industries, with a
commitment to ethical standards and societal well-being.
3. Continuously enhance faculty expertise through ongoing
training, ensuring the delivery of high-quality education and
mentorship.
4. Promote collaboration between academia and industry through
research and consultancy projects, providing students with
practical experiences and opportunities for conceptual learning.
Program Outcomes

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


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

2. Problem analysis: Identify, formulate, research literature, and analyse 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 public health and safety, and 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 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 the 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.
Program Educational Objectives

1. To impart in depth concepts of the subject in terms of both theoretical and practical aspects
to achieve excellent University results.
2. To produce technically sound engineering graduates who would fulfil the latest requirements
of computer science and IT industry at modest cost with the caliber of solving intricacies of
deeper programming concepts.
3. To inculcate the lessons of communication skills, teamwork spirit and professional attitude
to the budding engineering graduates.
4. In order to get versatile growth of students, participation of students in extracurricular
activities is also made compulsory; and also to develop ethical attitudes in the graduates so
that they can also become good citizens of the nation.
5. To develop leadership and entrepreneurship qualities in budding graduates so that they will
cherish and nourish the society and the nation with modern trends of digitization and
blossom it with their unparalleled technical expertise.
Course Outcomes

After Completing the course student should be able to:

CO1: Design, implement, and manipulate fundamental data structures such as arrays,
linked lists, stacks, queues, trees and graphs.

CO2: Develop the ability to analyze problems and choose appropriate data structures
and algorithms for efficient solutions, emphasizing algorithmic complexity and
optimization.

CO3: Gain expertise in memory management and understand the impact of data
structure choises on resource utilization, enabling efficient handling of large datasets
and optimizing program performance.

CO4: Enhance programming skills by applying data structures in real-world scenarios,


fostering the development of modular and reusable code for effective software design.

CO5: Cultivate analytical thinking to solve complex problems through the application
of various data structures, fostering a deep understanding of algorithmic paradigms and
their practical implications.
General Regulatory & Safety Rules
The following Regulations and Safety Rules must be observed in all concerned laboratory
locations.
1. It is the duty of all concerned parties who use any electrical laboratory to take all
reasonable steps to safeguard the HEALTH and SAFETY of themselves and all other
users and visitors.
2. Make sure that all equipment is properly working before using them for laboratory
exercises. Any defective equipment must be reported immediately to the Lab.
Instructors or Lab Technical Staff.
3. Students are allowed to use only the equipment provided in the experiment manual or
equipment used for senior project laboratory.
4. Power supply terminals connected to any circuit are only energized with the presence
of the Instructor or Lab. Staff.
5. Students should keep a safe distance from the circuit breakers, electric circuits or any
moving parts during the experiment.
6. Avoid any part of your body to be connected to the energized circuit and ground.
7. Switch off the equipment and disconnect the power supplies from the circuit before
leaving the laboratory.
8. Observe cleanliness and proper laboratory housekeeping of the equipment and other
related accessories.
9. Wear proper clothes and safety gloves or goggles required in working areas that
involves fabrications of printed circuit boards, chemicals process control system,
antenna communication equipment and laser facility laboratories.
10. Double check your circuit connections specifically in handling electrical power
machines,AC motors and generators before switching “ON” the power supply.
11. Make sure that the last connection to be made in your circuit is the power supply and
first thing to be disconnected is also the power supply.
12. Equipment should not be removed, transferred to any location without permission from
the laboratory staff.
13. Software installation in any computer laboratory is not allowed without the permission
from the Laboratory Staff.
14. Computer games are strictly prohibited in the computer laboratory.
15. Students are not allowed to use any equipment without proper orientation and actual
hands on equipment operation.
List of Experiments

S.No Name of the experiment Date Sign


Write a C++ program to search an element using :
1 (a) Linear Search
(b) Binary Search.
Write a C++ program to sort an array using :
2 (a) Merge Sort
(b) Quick Sort.
Write a C++ code to insert to and delete node from a
3
Singly Linked List.

Write a C++ code to insert to and delete node from a


4
Doubly Linked List.

5 Write a C++ code to implement a Stack using an array.

6 Write a C++ code to implement a Queue using an array.

Write a C++ code to implement a Queue using Singly


7
Linked List.

Write a C++ code to convert an infix expression into a


8
postfix expression using a stack.
Write a C++ code to add integers into a Binary Search
9 Tree. Also write functions to traverse BST using
Pre-order, In-order and Post-order traversal techniques.
Write a C++ code to traverse a Graph using :
10 (a) DFS
(b) BFS
Program 01
Write a C++ program to search an element using :
(a) Linear Search
(b) Binary Search.

#include <iostream>
using namespace std;

int LinearSearch(int arr[], int key, int size) {


int found = -1;
for(int i=0; i<size; i++) {
if(arr[i] == key) {
found = i;
return found;
}
}
return found;
}

int BinarySearch(int arr[], int key, int L, int R) {


int found = -1;
while(L<=R) {
int m = (L+R)/2;
if(arr[m] == key) {
found = m;
return found;
} else if(arr[m] < key) {
L = m+1; //key to be found is higher, so move L
forward
} else {
R = m-1;
}
}
return found;
}

int main() {
int arr[] = {4,8,10,14,21,22,36,62,77,81,91};
int size = sizeof(arr)/sizeof(arr[0]);
int result = BinarySearch(arr, 62, 0, size-1);
if(result!=-1)
cout << "Binary Search: Found at index " << result <<
endl;
else
cout << "Binary Search: Not Found\n";

result = LinearSearch(arr, 62, size);


if(result!=-1)
cout << "Linear Search: Found at index " << result <<
endl;
else
cout << "Binary Search: Not Found\n";
}

Output
Program 02
Write a C++ program to sort an array using :
(a) Merge Sort
(b) Quick Sort.

#include <iostream>
using namespace std;

int partition(int arr[], int low, int high) {


int pivot = arr[low];
int i = low;
int j = high;

while(i<j) {
while(i <= high && arr[i] <= pivot) i++;
while(j >= low && arr[j] > pivot) j--;
if(i<j) {
swap(arr[i], arr[j]);
}
}
swap(arr[low], arr[j]);

return j;
}

void quickSort(int arr[], int low, int high) {


int pIndex;
if(low < high) {
pIndex = partition(arr, low, high);
quickSort(arr, low, pIndex-1);
quickSort(arr, pIndex+1, high);
}
}

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1;
int n2 = right - mid;

int* L = new int[n1];


int* R = new int[n2];

for (int i = 0; i < n1; ++i)


L[i] = arr[left + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[mid + 1 + j];

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
++i;
} else {
arr[k] = R[j];
++j;
}
++k;
}

while (i < n1) {


arr[k] = L[i];
++i;
++k;
}

while (j < n2) {


arr[k] = R[j];
++j;
++k;
}

delete[] L;
delete[] R;
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int arr_size = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


for (int i = 0; i < arr_size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
mergeSort(arr, 0, arr_size - 1);

cout << "Merge Sorted array: ";


for (int i = 0; i < arr_size; ++i) {
cout << arr[i] << " ";
}
cout << endl;

quickSort(arr, 0, arr_size - 1);

cout << "Quick Sorted array: ";


for (int i = 0; i < arr_size; ++i) {
cout << arr[i] << " ";
}

return 0;
}

Output
Program 03
Write a C++ code to insert to and delete node from a Singly
Linked List.

#include <iostream>
using namespace std;

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

//Global head pointer of the SLL


Node *head = nullptr;

//Count total Nodes in SLL


int countNode(Node *ptr) {
int count=0;
while(ptr!=nullptr) {
count++;
ptr = ptr->next;
}
return count;
}

//Inserting a node at the beginning


void insertAtBeginning(Node *ptr, int num) {
//Create a new node
Node *n = new Node;
n->data = num;
n->next = nullptr;

if(head==NULL) { //if the SLL is empty


head = n; //make the new node as the head node
} else { // if the SLL is not empty
n->next = head; //make the new node point head
head = n; //head should now point to newly added
node
}
}

//Inserting a node at a given position


void insertAtPosition(Node *ptr, int pos, int num) {
//Count total nodes in SLL
int count = countNode(ptr);
//Check if the position given is invalid
if(pos>count+1 || pos < 1) {
cout << "Invalid position - " << pos << endl;
return;
}
//Create a new node
Node *n = new Node;
n->data = num;
n->next = nullptr;
//if pos = 1, insert at the beginning
if(pos==1) {
insertAtBeginning(ptr, num);
} else { // Traverse to the node just before the given
position
for(int i=1;i<pos-1;i++) {
ptr = ptr->next;
}
if(ptr!=nullptr) { // Insert the node at the given
position
n->next = ptr->next;
ptr->next = n;
}
}
}

//Appending a node in a linked list


void appendNode(Node *ptr, int num) {
Node *n = new Node;
n->data = num;
n->next = nullptr;
if(head==NULL) { //if the SLL is empty
head = n; //make the new node as the head node
} else {
while(ptr->next!=nullptr) {
ptr = ptr -> next;
}
ptr->next = n;
}
}

//Deleting a node at a given position


void deleteNode(Node *ptr, int pos) {
//Count total nodes in SLL
int count = countNode(ptr);
//Check if the position given is invalid
if(pos>count || pos < 1) {
cout << "Invalid position - " << pos << endl;
return;
}
//if pos = 1, shift the head to next node and delete
the head node
if(pos==1) {
head = head->next;
delete ptr;
} else { // Traverse to the node just before the given
position
for(int i=1;i<pos-1;i++) {
ptr = ptr->next;
}
Node *temp = ptr->next; //make temp point to the
node to be deleted
ptr->next = temp->next;
delete temp;
}
}

//Displaying a linked list


void show(Node *ptr) {
while(ptr!=nullptr) {
cout << ptr->data << " ";
ptr = ptr->next;
}
cout << endl;
}

int main()
{
insertAtBeginning(head,3);
insertAtBeginning(head,4);
insertAtBeginning(head,5);

insertAtPosition(head,2,10);

insertAtPosition(head,22,12);

show(head);

deleteNode(head,2);
show(head);

appendNode(head,2);
appendNode(head,1);

show(head);
return 0;
}
Output
Program 04
Write a C++ code to insert to and delete node from a Doubly
Linked List.

#include <iostream>
using namespace std;

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

Node *head=NULL, *tail=NULL;

Node *createNode(int data)


{
Node *n = new Node;
n->data = data;
n->prev = n->next = NULL;
return n;
}

void appendNode(int data)


{
Node *n = createNode(data);
if(head == NULL && tail == NULL)
{
head = n;
tail = n;
return;
}
tail->next = n;
n->prev = tail;
tail = n;
}

void prependNode(int data)


{
Node *n = createNode(data);
if(head == NULL && tail == NULL)
{
head = n;
tail = n;
return;
}
head->prev = n;
n->next = head;
head = n;
}

void printFwd()
{
Node *ptr = head;
if(ptr==NULL)
{
cout << "Linked list is empty\n";
return;
}
while(ptr!=NULL)
{
cout << ptr->data << " | ";
ptr = ptr->next;
}
cout << endl;
}

void insertNode(int data, int pos)


{
Node *n = createNode(data);
if(pos==1)
{
prependNode(data);
return;
}
Node *ptr = head;
for(int i=1;i<pos-1 && ptr->next!=NULL;i++)
{
ptr=ptr->next;
}
n->next = ptr->next;
n->prev = ptr;
if(ptr->next!=NULL)
ptr->next->prev = n;
ptr->next = n;
if(ptr==tail) {
tail = n;
}
}
void deleteNode(int pos)
{
if(pos < 1) {
cout << "Invalid Position" << endl;
return;
}
Node *ptr = head;
if(head==tail) {
delete ptr;
head = tail = nullptr;
return;
}

for(int i=1;i<pos && ptr->next!=NULL;i++)


{
ptr=ptr->next;
}

if(ptr->prev == nullptr)
{
head = head->next;
delete ptr;
head->prev = nullptr;
return;
}

if(ptr->next == nullptr)
{
tail = tail->prev;
delete ptr;
tail->next = nullptr;
return;
}

ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}

int main()
{
int arr[] = {10,20,30,40,50};
for(int i=0;i<5;i++)
{
appendNode(arr[i]);
}
printFwd();

insertNode(100,7);
printFwd();

deleteNode(6);
printFwd();
insertNode(45,10);
printFwd();
}
Output
Program 05
Write a C++ code to implement a Stack using an array.

#include <iostream>
using namespace std;

#define SIZE 10

typedef struct _stack {


int data[SIZE];
int top = -1;
} stack;

void push(stack *s, int n) {


s->top++;
if(s->top == SIZE-1) {
cout << "Stack is full" << endl;
return;
}
s->data[s->top] = n;
}

int pop(stack *s) {


if(s->top==-1) {
cout << "stack is empty" << endl;
return -1;
}
cout << s->data[s->top] << " ";
return s->data[s->top--];
}

void top(stack *s) {


if(s->top==-1) {
cout << "\nstack is empty" << endl;
return;
}
cout << "\n" << s->data[s->top] << " ";
}

int empty(stack *s) {


if(s->top==-1) return 1;
else return 0;
}
int main() {
stack s;
push(&s, 10);
push(&s, 20);
push(&s, 30);
push(&s, 40);

pop(&s);pop(&s);pop(&s);
top(&s);
}

Output
Program 06
Write a C++ code to implement a Queue using an array.

#include <iostream>
using namespace std;

typedef struct myq {


int size, front, rear, *q;
} Queue;

void init(Queue *x, int len) {


x->size = len;
x->rear = -1;
x->front = -1;
x->q = new int[x->size];
}

void nq(Queue *x, int num) {


if(x->rear==x->size-1) {
cout << "Queue is full\n";
return;
}
x->rear++;
x->q[x->rear] = num;
}

int dq(Queue *x) {


if(x->front==x->rear) {
cout << "Queue is empty\n";
return -1;
}
int temp = x->q[++x->front];
return temp;
}

int front(Queue *x) {


if(x->front==x->rear) return -1;
return x->q[x->front+1];
}

int rear(Queue *x) {


if(x->front==x->rear) return -1;
if(x->rear==-1) return -1;
return x->q[x->rear];
}
int main() {
Queue x;
init(&x, 10);
nq(&x, 10); nq(&x, 20); nq(&x, 30);
nq(&x, 40); nq(&x, 50); nq(&x, 60);

cout << front(&x) << " ";


cout << rear(&x) << endl;

dq(&x);

cout << front(&x) << " ";


cout << rear(&x) << endl;
}

Output
Program 07
Write a C++ code to implement a Queue using Singly Linked List.

#include <iostream>
using namespace std;

typedef struct _node {


int data;
struct _node *next;
} Node;

Node *front = NULL, *rear = NULL;

void nq(int num) {


Node *n = new Node;
n->data = num;
n->next = NULL;
if(front==NULL && rear==NULL) {
front = rear = n;
return;
}
rear->next = n;
rear = n;
}

int dq() {
if(front==NULL) {
return -1;
}
Node *temp = front;
int x = temp->data;
front = front->next;
free(temp);
return x;
}

void display() {
Node *temp = front;
while(temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
nq(10);
nq(20);
nq(30);
nq(40);
display();
cout << dq() << " ";
cout << dq() << endl;
display();
}

Output
Program 08
Write a C++ code to convert an infix expression into a postfix
expression using a stack.

#include <iostream>
#include <stack>
#include <vector>
#include <cctype>

using namespace std;

int preced(char ch) {


if(ch == '+' || ch == '-') {
return 1; //Precedence of + or - is
1
} else if(ch == '*' || ch == '/') {
return 2; //Precedence of * or / is 2
} else if(ch == '^') {
return 3; //Precedence of ^ is 3
} else {
return 0;
}
}

int main()
{
string infix = "A/(B+(C-D))*E";
vector<char> postfix;
stack<char> s;
for(int i=0;i<infix.length();i++)
{
char curr = infix[i];
if(isalnum(curr))
{
postfix.push_back(curr);
} else {

if(curr == '(') {
s.push(curr);
} else if(curr == ')') {
while(!s.empty() && s.top()!='(') {
postfix.push_back(s.top());
s.pop();
}
s.pop();
} else {
while(!s.empty() && preced(curr) <=
preced(s.top())) {
if(curr=='^' && s.top()=='^')
break;
postfix.push_back(s.top());
s.pop();
}
s.push(curr);
}
}

}
while(!s.empty()) {
postfix.push_back(s.top());
s.pop();
}

for(auto x:postfix)
cout << x << " ";
}

Output
Program 09
Write a C++ code to add integers into a Binary Search Tree. Also
write functions to traverse BST using
Pre-order, In-order and Post-order traversal techniques.

#include <iostream>
using namespace std;

struct Node {
Node* left;
Node* right;
int data;
};

Node *createNode(int data) {


Node *n = new Node;
n->data = data;
n->left = n->right = NULL;
return n;
}
Node* insert(Node *t, int key) {
Node *p;
if(t==NULL) {
p = createNode(key);
return p;
} else if(key < t->data) {
t->left = insert(t->left, key);
} else if(key > t->data) {
t->right = insert(t->right, key);
}

//key is equal to already existing element so just


return
return t;
}

void inorder(Node *p) {


if(p!=NULL) {
inorder(p->left);
cout << p->data << " ";
inorder(p->right);
}
}
void preorder(Node *p) {
if(p!=NULL) {
cout << p->data << " ";
preorder(p->left);
preorder(p->right);
}
}

void postorder(Node *p) {


if(p!=NULL) {
postorder(p->left);
postorder(p->right);
cout << p->data << " ";
}
}

int main()
{
Node *root = NULL;
int arr[] = {35,40,50,25,20,45,15};
int size = sizeof(arr)/sizeof(arr[0]);
root = insert(root, arr[0]);

for(int i=1;i<size;i++) {
insert(root, arr[i]);
}

cout << "Inorder: "; inorder(root);


cout << endl;

cout << "Preorder: "; preorder(root);


cout << endl;

cout << "Postorder: "; postorder(root);


cout << endl;
}

Output
Program 10
Write a C++ code to traverse a Graph using :
(a) Depth First Search (DFS)
(b) Breadth First Search (BFS)

#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100
// Structure to represent a node in the adjacency list
struct Node {
int vertex;
struct Node* next;
};
// Structure to represent the graph
struct Graph {
int numVertices;
struct Node* adjLists[MAX_NODES];
int visited[MAX_NODES];
};
// Queue structure for BFS
struct Queue {
int items[MAX_NODES];
int front;
int rear;
};
// Function prototypes
struct Graph* createGraph(int vertices);
void addEdge(struct Graph* graph, int src, int dest);
void DFS(struct Graph* graph, int vertex);
void BFS(struct Graph* graph, int startVertex);
struct Queue* createQueue();
void enqueue(struct Queue* q, int value);
int dequeue(struct Queue* q);
int isEmpty(struct Queue* q);
// Function to create a graph with the given number of vertices
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct
Graph));
graph->numVertices = vertices;
for (int i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Function to add an edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = dest;
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Since it's an undirected graph, add edge from dest to src
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = src;
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Depth First Search (DFS) function
void DFS(struct Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);
struct Node* temp = graph->adjLists[vertex];
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
// Breadth First Search (BFS) function
void BFS(struct Graph* graph, int startVertex) {
struct Queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
int currentVertex = dequeue(q);
printf("%d ", currentVertex);
struct Node* temp = graph->adjLists[currentVertex];
while (temp != NULL) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Function to create a queue
struct Queue* createQueue() {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = -1;
q->rear = -1;
return q;
}
// Function to check if the queue is empty
int isEmpty(struct Queue* q) {
return q->rear == -1;
}
// Function to add an element to the queue
void enqueue(struct Queue* q, int value) {
if (q->rear == MAX_NODES - 1) {
printf("\nQueue is full!");
} else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
// Function to remove an element from the queue
int dequeue(struct Queue* q) {
int item;
if (isEmpty(q)) {
printf("\nQueue is empty!");
return -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
q->front = q->rear = -1;
}
return item;
}
}
// Function to reset the visited array
void resetVisited(struct Graph* graph) {
for (int i = 0; i < graph->numVertices; i++) {
graph->visited[i] = 0;
}
}
// Main function
int main() {
int vertices, edges, src, dest, startVertex;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
struct Graph* graph = createGraph(vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);
printf("Enter the edges (source and destination):\n");
for (int i = 0; i < edges; i++) {
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
printf("Enter the starting vertex for DFS: ");
scanf("%d", &startVertex);
printf("Depth First Search starting from vertex %d:\n",
startVertex);
DFS(graph, startVertex);
resetVisited(graph); // Reset visited array for BFS
printf("\n\nEnter the starting vertex for BFS: ");
scanf("%d", &startVertex);
printf("Breadth First Search starting from vertex %d:\n",
startVertex);
BFS(graph, startVertex);
return 0;
}

Output

You might also like