LAB Re
LAB Re
DATA STRUCTURES
AND
ANALYSIS OF ALGORITHMS
CSD3009
Submitted by
BACHELOR OF TECHNOLOGY
in
Artificial intelligence and machine learning
KOTHRIKALAN, SEHORE
MADHYA PRADESH - 466114
Feb (2023)
INSERTION
Output
TRAVERSAL & CREATION
Output
DELETION
Output
Course Code: CSD3009
Course Name: DATA-STRUCTURES-AND-ANALYSIS-OF-ALGORITHMS
Registration No: 21BSA10163
Name: Harsh Kumar Sahu
Lab 2
Q. Write a program that uses functions to perform the following operations on doubly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal
#include <stdio.h>
#include <stdlib.h>
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Function used in this program
*/
void createList(int n);
void displayListFromFirst();
void displayListFromEnd();
int main()
{
int n, choice;
head = NULL;
last = NULL;
if(choice==1)
{
displayListFromFirst();
}
else if(choice == 2)
{
displayListFromEnd();
}
return 0;
}
/**
* Create a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));
if(head != NULL)
{
printf("Enter data of 1 node: ");
scanf("%d", &data);
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Create rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode != NULL)
{
printf("Enter data of %d node: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; // Link new node with the previous
node
newNode->next = NULL;
/**
* Displays the content of the list from beginning to end
*/
void displayListFromFirst()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
printf("\n\nDATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
/**
* Display the content of the list from last to first
*/
void displayListFromEnd()
{
struct node * temp;
int n = 0;
if(last == NULL)
{
printf("List is empty.");
}
else
{
temp = last;
printf("\n\nDATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of last-%d node = %d\n", n, temp->data);
n++;
Screenshot:-
output
Insertion:
#include <stdio.h>
#include <stdlib.h>
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Function used in this program
*/
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtEnd(int data);
void insertAtN(int data, int position);
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
/*
* Run forever until user chooses 0
*/
while(choice != 0)
{
/*
* Menu creation to use the program
*/
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Insert node - at beginning\n");
printf("3. Insert node - at end\n");
printf("4. Insert node - at N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
/*
* Choose from different menu operation
*/
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
printf("Enter data of first node : ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 3:
printf("Enter data of last node : ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 4:
printf("Enter the position where you want to insert new node:
");
scanf("%d", &n);
printf("Enter data of %d node : ", n);
scanf("%d", &data);
insertAtN(data, n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}
printf("\n\n\n\n\n");
}
return 0;
}
/**
* Creates a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
/*
* Create and link the head node
*/
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Create and link rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;
/**
* Display content of the list from beginning to end
*/
void displayList()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
/**
* Inserts a new node at the beginning of the doubly linked list
* @data Data of the first node i.e. data of the new node
*/
void insertAtBeginning(int data)
{
struct node * newNode;
if(head == NULL)
{
printf("Error, List is Empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head; // Point to next node which is currently head
newNode->prev = NULL; // Previous node of first node is NULL
/**
* Inserts a new node at the end of the doubly linked list
* @data Data of the last node i.e data of the new node
*/
void insertAtEnd(int data)
{
struct node * newNode;
if(last == NULL)
{
printf("Error, List is empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = last;
last->next = newNode;
last = newNode;
/**
* Inserts a node at any position in the doubly linked list
* @data Data of the new node to be inserted
* @position Position where to insert the new node
*/
void insertAtN(int data, int position)
{
int i;
struct node * newNode, *temp;
if(head == NULL)
{
printf("Error, List is empty!\n");
}
else
{
temp = head;
i=1;
if(position == 1)
{
insertAtBeginning(data);
}
else if(temp == last)
{
insertAtEnd(data);
}
else if(temp!=NULL)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = temp->next; // Connect new node with n+1th node
newNode->prev = temp; // Connect new node with n-1th node
if(temp->next != NULL)
{
/* Connect n+1th node with new node */
temp->next->prev = newNode;
}
/* Connect n-1th node with new node */
temp->next = newNode;
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Functions used in this program
*/
void createList(int n);
void displayList();
void deleteFromBeginning();
void deleteFromEnd();
void deleteFromN(int position);
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
/*
* Run forever until user chooses 0
*/
while(choice != 0)
{
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Delete node - from beginning\n");
printf("3. Delete node - from end\n");
printf("4. Delete node - from N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
deleteFromBeginning();
break;
case 3:
deleteFromEnd();
break;
case 4:
printf("Enter the node position which you want to delete: ");
scanf("%d", &n);
deleteFromN(n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}
printf("\n\n\n\n\n");
}
return 0;
}
/**
* Creates a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
/*
* Creates and links the head node
*/
head = (struct node *)malloc(sizeof(struct node));
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Create and link rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");
while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);
n++;
/**
* Delete or remove the first node of the doubly linked list
*/
void deleteFromBeginning()
{
struct node * toDelete;
if(head == NULL)
{
printf("Unable to delete. List is empty.\n");
}
else
{
toDelete = head;
head = head->next; // Move head pointer to 2 node
if (head != NULL)
head->prev = NULL; // Remove the link to previous node
/**
* Delete or remove the last node of the doubly linked list
*/
void deleteFromEnd()
{
struct node * toDelete;
if(last == NULL)
{
printf("Unable to delete. List is empty.\n");
}
else
{
toDelete = last;
if (last != NULL)
last->next = NULL; // Remove link to of 2nd last node with last node
/**
* Delete node from any position in the doubly linked list
*/
void deleteFromN(int position)
{
struct node *current;
int i;
current = head;
for(i=1; i<position && current!=NULL; i++)
{
current = current->next;
}
if(position == 1)
{
deleteFromBeginning();
}
else if(current == last)
{
deleteFromEnd();
}
else if(current != NULL)
{
current->prev->next = current->next;
current->next->prev = current->prev;
#include <stdio.h>
#include <stdlib.h>
// Create a node
struct Node {
int data;
struct Node* next;
};
new_node->next = (*head_ref);
// Move head to new node
(*head_ref) = new_node;
}
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
last->next = new_node;
return;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;
free(temp);
}
// Search a node
int searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
// Driver program
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);
int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
printf("\n%d is found", item_to_find);
} else {
printf("\n%d is not found", item_to_find);
}
sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
}
Output:-
LAB-4
Q.Write a program to perform the following operation: a) Insert an element into
a binary search tree. B) delete àn element form a binary search tree. C) search
for a key element in a binary search tree
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
};
Output:
LAB-5
Q.Write algorithms for Breadth First Search (BFS) and Depth First Search (DFS)
in a graph. Also, implement them using a programming language
1. Take the empty queue and bool type array (visit) initialise with FALSE.
2. Push the starting node in the queue and set the value TRUE for this node in
visited array.
3. Pop out the front node of the queue and print the node.
4. Push the adjacent node of pop node in queue which are not visited. Set the
value TRUE in visited array of adding node.
5. Repeat step 3 and 4 until the queue becomes empty.
1. Take the empty stack and bool type array (visit) initialise with FALSE.
2. Push the starting node in the stack and set the value TRUE for this node in
visited array.
3. Pop the top node from the stack and print that node.
4. Push the adjacent node of pop node in the stack which is not visited. Set the
value TRUE in visited array of adding node.
5. Repeat step 3 and 4until the stack becomes empty.
So, here we also look that the BFS and DFS algorithm is mostly similar in above
iterative approaches, only one difference is that in BFS that we will use the queue
and in DFS we will use the stack because need goes to depth for DFS.
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
//add the edge in graph
void edge(vector<int>adj[],int u,int v){
adj[u].push_back(v);
}
//function for bfs traversal
void bfs(int s,vector<int>adj[],bool visit[]){
queue<int>q;//queue in STL
q.push(s);
visit[s]=true;
while(!q.empty()){
int u=q.front();
cout<<u<<" ";
q.pop();
//loop for traverse
for(int i=0;i<adj[u].size();i++){
if(!visit[adj[u][i]]){
q.push(adj[u][i]);
visit[adj[u][i]]=true;
}
}
}
}
//function for dfs traversal
void dfs(int s,vector<int>adj[],bool visit[]){
stack<int>stk;//stack in STL
stk.push(s);
visit[s]=true;
while(!stk.empty()){
int u=stk.top();
cout<<u<<" ";
stk.pop();
//loop for traverse
for(int i=0;i<adj[u].size();i++){
if(!visit[adj[u][i]]){
stk.push(adj[u][i]);
visit[adj[u][i]]=true;
}
}
}
}
//main function
int main(){
vector<int>adj[5];//vector of array to store the graph
bool visit[5];//array to check visit or not of a node
//initially all node are unvisited
for(int i=0;i<5;i++){
visit[i]=false;
}
//input for edges
edge(adj,0,2);
edge(adj,0,1);
edge(adj,1,3);
edge(adj,2,0);
edge(adj,2,3);
edge(adj,2,4);
cout<<"BFS traversal is"<<" ";
//call bfs funtion
bfs(0,adj,visit);//1 is a starting point
cout<<endl;
//again initialise all node unvisited for dfs
for(int i=0;i<5;i++){
visit[i]=false;
}
cout<<"DFS traversal is"<<" ";
//call dfs function
dfs(0,adj,visit);//1 is a starting point
}
OUTPUT:-
1.Bubble sort
#include<iostream>
arr[j] = arr[j+1];
arr[j+1] = temp;
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
return 0;
2.Insertion sort
#include<iostream>
int key, j;
key = arr[i];
j = i-1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
int main() {
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
cout << "Sorted array is: \n";
return 0;
3.Selection sort
#include<iostream>
int i, j, min_idx;
min_idx = i;
min_idx = j;
arr[min_idx] = arr[i];
arr[i] = temp;
int main() {
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
return 0;
4.Merge sort
#include<iostream>
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
i = 0;
j = 0;
k = l;
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
merge(arr, l, m, r);
int main() {
int n = sizeof(arr)/sizeof(arr[0]);
mergeSort(arr, 0, n-1);
return 0;
5.Quick sort
#include<iostream>
i++;
arr[i] = arr[j];
arr[j] = temp;
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
quickSort(arr, pi + 1, high);
int main() {
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
return 0;
}
LAB-7
C implementation of the Prim's algorithm for finding the minimum spanning tree of
a connected, undirected graph:
This implementation uses the Prim's algorithm to find the minimum spanning tree of
a connected, undirected graph. It starts from a given vertex and iteratively adds the
vertex that is not yet in the tree, but has the smallest edge with a vertex that is
already in the tree. It uses a 2D array called "graph" to store the edges, and a 1D
array called "visited" to keep track of which vertices are already in the tree. It prints
the edges and the total weight of the minimum spanning tree.
It uses the adjacency matrix representation of the graph. If the graph is sparse, you
can use adjacency list representation, which will be more memory efficient.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int n, m;
int graph[MAX_VERTICES][MAX_VERTICES];
bool visited[MAX_VERTICES];
int main() {
int i, j;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
graph[i][j] = 0;
}
}
for (i = 0; i < m; i++) {
int x, y, w;
scanf("%d %d %d", &x, &y, &w);
graph[x][y] = w;
graph[y][x] = w;
}
prim(0);
return 0;
}
C implementation of the Kruskal's algorithm for finding the minimum spanning tree
of a connected, undirected graph:
This implementation uses the union-find data structure to keep track of the
connected components in the graph. It sorts the edges by weight, and then iterates
through them in increasing order of weight, adding each edge to the minimum
spanning tree if its endpoints belong to different connected components. The edges
are stored in an array called edges and the vertices are stored in an array called
vertices.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int x, y, w;
} Edge;
Edge edges[MAX_EDGES];
int parent[MAX_VERTICES];
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
int main() {
int n, m, i;
scanf("%d %d", &n, &m);
for (i = 0; i < m; i++)
scanf("%d %d %d", &edges[i].x, &edges[i].y, &edges[i].w);
kruskal(n, m);
return 0;
}