LAB - XBC206 - Data Structure Lab Manual
LAB - XBC206 - Data Structure Lab Manual
Periyar Nagar, Vallam Thanjavur - 613 403, Tamil Nadu, India Phone:
+91 - 4362 - 264600 Fax: +91- 4362 - 264660
Email: [email protected] Web: www. pmu.edu
DEPARTMENT VISION
DEPARTMENT MISSION
DM1 To construct the software related technical skills among the students.
DM2 To practice the cutting-edge technologies in the various areas of digital design
and software development.
Based on the mission of the department, the programme educational objective is formulated as .
The B.Sc. Computer Science dedicated to produce graduates who have ability to
PEO4 handle the customers and stakeholders effectively with the awareness of
human values and ethical concerns.
PEO5 pursue lifelong learning through the cutting-edge Learning Management
Systems and thus satisfy the up-to-date industry expectations.
PO 1 identify and analyze the acquainted or unacquainted real time issues and afford
solution using the necessary computing, mathematical and basic science skill set.
PO 2 design and develop algorithms for providing an appropriate solution to gratify the
industrial and social needs.
PO 3 express ideas and thoughts effectively to the team members and customers
through written and oral communication.
PO 5 inspire and guide the team members using management skills to achieve the target
in an efficient and smooth way.
PSO1 provide the professional user friendly interface with the help of state-of- the-art
tools and technologies.
PSO2 design the interactive& responsive web based and mobile applications.
No
1.1 Create a Linked List & Display the Elements in the List 6
2.3 Queue 36
Procedure
1. Node Definition:
● Define a structure (or class, depending on the programming language) that represents a node in the
linked list. This structure typically contains two components:
● Data: The actual data or value associated with the node.
● Next: A reference or pointer to the next node in the sequence.
2. Initialization:
● Create a head pointer that points to the first node in the list. Initially, the head can be set to NULL if
the list is empty.
3. Insertion:
● To insert a new node into the linked list:
● Create a new node with the desired data.
● Update the next pointer of the new node to point to the current first node.
● Update the head pointer to point to the new node.
4. Deletion:
● To delete a node from the linked list:
● Find the node to be deleted.
● Update the next pointer of the previous node to skip the node to be deleted.
● Free the memory allocated to the deleted node.
Program Coding:
/*
* C program to create a linked list and display the elements in the list
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main()
{
struct node
{
int num;
struct node *ptr;
};
typedef struct node NODE;
first = 0;
clrscr();
while (choice)
{
head = (NODE *)malloc(sizeof(NODE));
printf("Enter the data item\n");
scanf("%d", &head-> num);
if (first != 0)
{
temp->ptr =
head; temp =
head;
}
else
{
first = temp = head;
}
fflush(stdin);
printf("Do you want to continue(Type 0 or 1)?\n");
scanf("%d", &choice);
temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
printf("\n status of the linked list is\n");
while (temp != 0)
{
printf("%d=>", temp->num);
count++;
temp = temp -> ptr;
}
printf("NULL\n");
printf("No. of nodes in the list = %d\n", count);
getch();
}
Output:
Result:
Thus to write a c program to the creation of list of elements where the size of the list, elements to be
inserted and deleted is dynamically given as input has been verified.
Aim:
To implement a C program to insert and delete elements from the singly linked list.
Procedure
1. Node Definition:
a. Define a structure (or class, depending on the programming language) that represents a node in the
linked list. This structure typically contains two components:
i. Data: The actual data or value associated with the node.
ii. Next: A reference or pointer to the next node in the sequence.
2. Initialization:
a. Create a head pointer that points to the first node in the list. Initially, the head can be set to NULL if
the list is empty.
3. Insertion:
a. To insert a new node into the linked list:
i. Create a new node with the desired data.
ii. Update the next pointer of the new node to point to the current first node.
iii. Update the head pointer to point to the new node.
4. Deletion:
● To delete a node from the linked list:
● Find the node to be deleted.
● Update the next pointer of the previous node to skip the node to be deleted.
● Free the memory allocated to the deleted node.
Program:
#include<stdlib.h>
#include <stdio.h>
#include<conio.h>
void create();
void display();
void insert_begin();
void insert_end();
void insert_pos();
void delete_begin();
void delete_end();
void delete_pos();
struct node
{
int info;
struct node *next;
};
struct node *start=NULL;
void main()
{
int choice;
clrscr();
while(1)
{
switch(choice)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert_begin();
break;
case 4:
insert_end();
break;
case 5:
insert_pos();
break;
case 6:
delete_begin();
break;
case 7:
delete_end();
break;
case 8:
delete_pos();
break;
case 9:
exit(0);
break;
default:
break;
}
}
getch();
}
void create()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:\n");
exit(0);
}
printf("\nEnter the data value for the node:\t");
scanf("%d",&temp->info);
temp->next=NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
}
}
void display()
{
struct node *ptr;
if(start==NULL)
{
printf("\nList is empty:\n");
return;
}
else
{
ptr=start;
printf("\nThe List elements are:\n");
while(ptr!=NULL)
{
printf("%dt",ptr->info );
ptr=ptr->next ;
}
}
}
void insert_begin()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:\n");
return;
}
printf("\nEnter the data value for the node:\t" );
scanf("%d",&temp->info);
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
temp->next=start;
start=temp;
}
}
void insert_end()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:\n");
return;
}
printf("\nEnter the data value for the node:\t" );
scanf("%d",&temp->info );
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next !=NULL)
{
ptr=ptr->next ;
}
ptr->next =temp;
}
}
void insert_pos()
{
void delete_end()
{
struct node *temp,*ptr;
if(start==NULL)
{
printf("\nList is Empty:");
exit(0);
}
else if(start->next ==NULL)
{
ptr=start;
start=NULL;
printf("\nThe deleted element is:%d\t",ptr->info);
free(ptr);
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
temp=ptr;
ptr=ptr->next;
}
temp->next=NULL;
printf("\nThe deleted element is:%d\t",ptr->info);
free(ptr);
}
}
void delete_pos()
{
int i,pos;
struct node *temp,*ptr;
if(start==NULL)
{
printf("\nThe List is Empty:\n");
exit(0);
}
else
{
printf("\nEnter the position of the node to be deleted:\t");
scanf("%d",&pos);
if(pos==0)
{
ptr=start;
start=start->next ;
printf("\nThe deleted element is:%d\t",ptr->info );
free(ptr);
}
else
{
ptr=start;
for(i=0;i<pos;i++) { temp=ptr; ptr=ptr->next ;
if(ptr==NULL)
{
printf("\nPosition not Found:\n");
return;
}
}
temp->next =ptr->next ;
printf("\nThe deleted element is:%d\t",ptr->info );
free(ptr);
}
}
}
Output:
Result:
Thus the C program for the inserting and deleting the elements in the linked list is
implemented and verified successfully.
Aim:
To implement C Program finds the largest element in a doubly linked list.
Procedure :
struct node
{
int num;
struct node *next;
struct node
*prev;
};
void main()
{
struct node *p =
NULL; int n;
printf("Enter data into the
list\n"); create(&p);
n = max(p);
printf("The maximum number entered in the list is %d.\n",
n); release (&p);
getch();
}
do
{
printf("Enter number:
"); scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct
node)); temp->num = c;
temp->next = NULL;
temp->prev =
NULL; if (*head ==
NULL)
{
*head = temp;
}
else
{
rear->next = temp;
temp->prev =
rear;
}
rear = temp;
printf("Do you wish to continue [yes:1/No:0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
*head = (*head)->next;
while ((*head) !=
NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}
OUTPUT:
Enter data into the list
Enter number: 10
Do you wish to continue [yes:1/No:0]: 1
Enter number: 50
Do you wish to continue [yes:1/No:0]: 1
Enter number: 41
Do you wish to continue [yes:1/No:0]: 1
Enter number: 67
Do you wish to continue [yes:1/No:0]: 0
Result:
Procedure :
1. Initialization:
● Create an empty stack. You can use an array or a linked list to implement a stack, depending on your
preference and the programming language.
2. Push (Insert):
● To add an element to the stack (push operation):
● Check if the stack is full (if using a fixed-size array implementation).
● If not full, add the element to the top of the stack.
● Update the top pointer to the new top element.
3. Pop (Delete):
● To remove the top element from the stack (pop operation):
● Check if the stack is empty.
● If not empty, remove the element from the top of the stack.
● Update the top pointer to the next element in the stack.
4. Peek (Top):
● To view the top element without removing it:
● Check if the stack is empty.
● If not empty, retrieve the element at the top of the stack.
5. isEmpty:
● Check if the stack is empty.
6. isFull (if using a fixed-size array):
● Check if the stack is full.
7. Size:
● Get the current number of elements in the stack.
Program:
#include<stdio.h>
#include<conio.h>
#define Size 4
int main()
{
int choice;
clrscr();
while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);
void Push()
{
int x;
if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
stack[Top]=x;
}
}
void Pop()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
p
ri
nt
}
f(
}
"\
n
P
o
p
p
e
d
el
e
m
e
nt
:
%
d
",
st
a
c
k
[
T
o
p
])
;
T
o
p
=
T
o -
p 1;
void show()
{
int i;
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
p
ri
n
} tf
(
}
"\
n
E
l
e
m
e
n
ts
p
r
e
s
e
n
t
i
n
t
h
e
st
a
c
k
:
\
n
"
);
f
o
r(
i
=
T
o
p
;i
>
=
0
;-
-i
)
printf("%d\n",stack[i]);
OUTPUT:
Result:
Thus the C program to implement stack using array has been executed and verified successfully.
Aim:
To implement the C program for Infix expression to postfix conversion using stack.
Procedure :
Stack Initialization:
● Define a structure for the stack and create functions to initialize, check for empty or full, push, and pop
elements from the stack.
Evaluate Postfix Expression:
● Create a function to evaluate a postfix expression using a stack.
Infix to Postfix Conversion:
● Create a function to convert an infix expression to postfix notation.
Get Operator Precedence:
● Create a function to get the precedence of an operator for proper infix to postfix conversion.
Display Result:
● Create a function to display the result of the postfix expression.
Program
#include<stdio.h>
#include<conio.h>
char stack[20];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x ==
'-') return 1;
if(x == '*' || x ==
'/') return 2;
return 0;
}
void main()
{
char exp[100];
char *e, x;
clrscr();
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) !=
'(') printf("%c ",
x);
}
else
{
while(priority(stack[top]) >=
priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
getch();
}
Output:
Result:
Thus the C program to implement the application of stack using array has been executed and verified
successfully.
Aim:
To implement the C program for queue using array.
1. Initialization:
Create an empty queue. You can use an array or a linked list to implement a queue, depending on
your preference and the programming language.
2. Enqueue (Insert):
To add an element to the queue (enqueue operation):
● Check if the queue is full (if using a fixed-size array implementation).
● If not full, add the element to the rear of the queue.
● Update the rear pointer to the new rear element.
3. Dequeue (Delete):
To remove the front element from the queue (dequeue operation):
● Check if the queue is empty.
● If not empty, remove the element from the front of the queue.
● Update the front pointer to the next element in the queue.
4. Front (Peek):
To view the front element without removing it:
● Check if the queue is empty.
● If not empty, retrieve the element at the front of the queue.
5. isEmpty:
Check if the queue is empty.
6. isFull (if using a fixed-size array):
Check if the queue is full.
7. Size:
Get the current number of elements in the queue.
Program:
#include <stdio.h>
#include<conio.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int choice;
clrscr();
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice :
"); scanf("%d", &choice);
switch(choice)
{
case 1: i
n
s
case 2: e
r
t
case 3: (
)
;
case 4: b
r
e
a
k
;
d
e
l
e
t
e
(
)
;
b
r
e
a
k
;
d
i
s
p
l
a
y
(
)
;
b
r
e
a
k
;
exit(1);
default:
printf("Wrong choice \n");
}
}
getch();
}
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if(front== - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if(front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for(i = front; i <= rear;
i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Output:
Result:
Thus the C program to implement queue using array has been executed and verified successfully.
Aim:
To implement the C program to visit each node in a binary tree using tree traversal techniques.
Procedure
1. Initialization:
● Create an empty binary tree.
2. Insertion:
● To insert a new element into the binary tree:
● Start at the root.
● If the tree is empty, create a new node as the root.
● Otherwise, traverse the tree from the root:
● If the value to be inserted is less than the current node's value, move to the left child.
● If the value is greater, move to the right child.
● Repeat the process until an empty spot is found, then insert the new node.
3. Deletion:
● To delete a node from the binary tree:
● Locate the node to be deleted.
● If the node has no children, simply remove it.
● If the node has one child, replace the node with its child.
● If the node has two children:
● Find the node's in-order successor (the smallest node in the right subtree).
● Replace the node's value with the in-order successor's value.
● Delete the in-order successor node.
4. Minimum and Maximum:
● To find the minimum value in the binary tree, follow the left child pointers until you reach a leaf
node.
● To find the maximum value, follow the right child pointers until you reach a leaf node.
Output:
Result:
Thus the C program to implement the tree traversals in a binary tree has been executed and verified
successfully.
Aim:
To implement a C Program to search an element in a list using linear search and binary search
algorithm.
Procedure :
1. Linear Search:
● Create a function linear_search that takes a list (arr) and an element to search for (x) as
parameters.
● Use a loop to iterate through each element in the list.
● Check if the current element is equal to the target element (x).
● If found, return the index of the element.
● If the loop completes without finding the element, return -1 to indicate that the element is not in the
list.
2. Binary Search:
● Create a function binary_search that assumes the input list is sorted and takes a sorted list (arr)
and an element to search for (x) as parameters.
● Initialize two pointers (low and high) to represent the range of the search.
● Use a while loop to continue searching while the low pointer is less than or equal to the high
pointer.
● Calculate the middle index (mid) of the current search range.
● Check if the element at the middle index is equal to the target element (x).
● If found, return the index of the element.
● If the target element is less than the middle element, update the high pointer to narrow the search to
the lower half.
● If the target element is greater than the middle element, update the low pointer to narrow the search
to the upper half.
● If the loop completes without finding the element, return -1 to indicate that the element is not in the
list.
Program:
/* Program to implement linear search and Binary search */
#include <stdio.h>
#include <conio.h>
void main()
{
/* Declare variables - array_of_number, search_key, i, j, low, high*/
int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int
n); clrscr();
/* read the elements of array */
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
/* Get the Search Key element for Linear Search */
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);
/* Choice of Search Algorithm */
printf("
\n"); printf("1.LINEAR
SEARCH\n"); printf("2.BINARY
SEARCH\n");
printf(" \n");
printf("ENTER YOUR
CHOICE:");
scanf("%d",&choice)
; switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++
)
{
if(search_key == array[i])
{
location = i;
printf(" \n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf(" \n");
}
}
}
/* Binary Search to find Search Key */
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high;
low = 1;
high = n;
mid = (low +
high)/2; i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1;
high = mid+1;
mid = (low+high)/2;
}
else
{
low =
mid+1; high
= n;
mid = (low+high)/2;
}
}
printf("
_\n"); printf("location=%d\t",mid);
printf("Search_Key=%d Found!\n",search_key);
printf("
_\n");
}
Output
Procedure :
1. Start with the Second Element:
● Begin the sorting process from the second element (index 1) because the first element (at
index 0) is considered already sorted.
2. Compare and Insert:
● Compare the current element with the elements on its left.
● Insert the current element into its correct position in the sorted part of the array by shifting
larger elements to the right.
3. Repeat:
● Repeat the process for each unsorted element in the array until the entire array is sorted.
Program:
// C program for
insertion sort
#include <math.h>
#include <stdio.h>
/* Move elements of
arr[0..i-1], that are greater
than key, to one position
ahead of their current
position */
while (j >= 0 && arr[j] >
key) { arr[j + 1] =
arr[j]; //12, arr[1] = 12 j
= j - 1; // 0-1 = -1
}
arr[j + 1] = key; // arr[0] = 11
}
}
// A utility function to print an
array of size n void printArray(int
arr[], int n)
{
int i;
for (i = 0; i
< n; i++)
printf("%
d ",
arr[i]);
printf("\n");
}
void main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) /
sizeof(arr[0]); clrscr();
insertionS
ort(arr, n);
printArray
(arr, n);
getch();
}
Output:
5 6 11 12 13
Result:
Thus the C program to sort the list using insertion sort has been executed and verified
successfully.
Aim:
To write a C program to sort the list of elements using bubble sort algorithm.
Procedure :
Program:
// C program for implementation of Bubble sort
#include <stdio.h>
#include<conio.h>
Procedure
1. Choose a Pivot:
● Select a pivot element from the array. The choice of the pivot can be arbitrary (e.g., the last element,
the middle element, or a random element).
2. Partition:
● Partition the array into two sub-arrays: elements less than the pivot and elements greater than the
pivot.
3. Recursively Sort Sub-arrays:
● Recursively apply the Quick Sort algorithm to the two sub-arrays.
4. Combine:
● Combine the sorted sub-arrays and the pivot back into a single sorted array.
Program:
#include <stdio.h>
#include<conio.h>
void quick_sort(int[],int,int);
int partition(int[],int,int);
void main()
{
int a[50],n,i;
clrscr();
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array
elements:"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick_sort(a,0,n-1);
printf("\nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
Result:
Thus the C program to sort the list using quick sort has been executed and verified
successfully.
Aim:
To write a C program to create a binary search tree and insert and delete the element from
the tree.
Procedure:
Initialization:
● Create a pointer to represent the root of the BST, initially set to NULL.
Insertion:
● Implement a function to insert a new node with a given value into the BST.
● If the tree is empty, create a new node as the root.
● Otherwise, traverse the tree based on the comparison of values to find the correct
position for insertion.
Program
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int key;
struct node *left;
struct node *right;
}Node;
/*for creating new node */
Node * newNode(int key){
return temp;
}
/*for inserting the key, newNode is the node needed to be inserted */
Node * insert(Node *p, Node *nwNode){
if(!p){
printf("Key %d\tinserted\n", nwNode->key);
return nwNode;
}
if(nwNode->key >
p->key){ insert(p->right,
nwNode); if(!(p->right))
p->right = nwNode;
}
else{
insert(p->left,
nwNode); if(!(p->left))
p->left = nwNode;
}
return p;
}
/* for searching the key */
void search(Node *p, int searchKey){
if(!p){
printf("No key found for value - %d.\n", searchKey);
return ;
}
if(p->key == searchKey){
printf("Key %d\tfound\n", searchKey);
}
}
/* inorder successor in BST will be the minimum key in right subtree */
Node * getInSuccessor(Node *p){
while(p->left != NULL)
p = p->left; //this will give the minimum key
return p;
}
free(p);
return
temp;
}
void main(void)
{
Node *root =
NULL; Node
*newRoot; clrscr();
root = insert(root, newNode(50));
insert(root, newNode(80));
insert(root, newNode(30));
insert(root, newNode(40));
insert(root, newNode(20));
insert(root, newNode(100));
search(root, 50);
search(root, 10);
getch();
}
OUTPUT
Result:
Thus the C program to create a binary search tree and insert and delete the element from the
tree has been executed and verified successfully.
Aim:
To write a C program to implement the Breadth First Search (BFS) traversal for directed
Graph using a Queue.
1. Create a Queue:
● Create an empty queue to keep track of the vertices to be processed.
2. Enqueue the Source Vertex:
● Enqueue the source vertex into the queue.
3. Mark the Source Vertex as Visited:
● Mark the source vertex as visited to avoid revisiting it.
4. While the Queue is Not Empty:
● While the queue is not empty, do the following steps:
● Dequeue a vertex from the queue.
● Process the dequeued vertex (print it or perform some other operation).
● Enqueue all the unvisited neighbors of the dequeued vertex.
● Mark each visited neighbor as visited.
5. Repeat Until the Queue is Empty:
● Repeat the process until the queue is empty.
Program:
#include<stdio.h>
#include<conio.h>
#define initial 1
#define waiting 2
#define visited 3
int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);
void BF_Traversal()
{
int v;
for(v=0; v<n;
v++) state[v] =
initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}
void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;
while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}
void insert_queue(int vertex)
{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}
int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}
int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}
delete_item = queue[front];
front = front+1;
return delete_item;
}
void create_graph()
{
int count,max_edge,origin,destin;
Output:
Result:
Thus the C program to Breadth First Search (BFS) traversal for directed Graph using a Queue
has been executed and verified successfully.
Aim:
To write a C program to implement DFS Algorithm for Connected Graph using a stack.
DFS:
Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and uses a stack to
remember to get the next vertex to start a search, when a dead end occurs in any iteration.
It employs the following rules.
▪ Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
▪ Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the
vertices from the stack, which do not have adjacent vertices.)
Program:
/* C Program to implement DFS Algorithm for Connected Graph */
#include<stdio.h>
#include<conio.h>
#define initial 1
#define visited 2
void DF_Traversal();
void DFS(int v);
void create_graph();
int stack[MAX];
int top = -1;
void push(int
v); int pop();
int isEmpty_stack();
void main()
{
clrscr();
create_graph();
DF_Traversal();
getch();
}/*End of main()*/
void DF_Traversal()
{
int v;
void DFS(int v)
{
int i;
push(v);
while(!isEmpty_stack())
{
v = pop();
if(state[v]==initial)
{
printf("%d ",v);
state[v]=visited
;
}
for(i=n-1; i>=0; i--)
{
if(adj[v][i]==1 &&
state[i]==initial) push(i);
}
}
}/*End of DFS( )*/
void push(int v)
{
if(top == (MAX-1))
{
printf("\nStack Overflow\n");
return;
}
top=top+1;
stack[top] = v;
}/*End of push()*/
int pop()
{
int v;
if(top == -1)
{
p
r
} i
else n
t
{ f
(
"
\
} n
S
t
a
c
k
U
n
d
e
r
f
l
o
w
\
n
"
)
;
e
x
i
t
(
1
)
;
v
=
s
t
a
c
k
[
t
o
p
]
;
t ;
o r
p e
= t
t u
o r
p n
- v
1 ;
}/*End of pop()*/
int isEmpty_stack( )
{
if(top == -1)
return 1;
else
return 0;
}/*End if isEmpty_stack()*/
void create_graph()
{
int i,max_edges,origin,destin;
for(i=1;i<=max_edges;i++)
{
printf("\nEnter edge %d( -1 -1 to quit ) : ",i);
scanf("%d %d",&origin,&destin);
adj[origin][destin] = 1;
Output:
Result:
Thus the C program to implement DFS Algorithm for Connected Graph using a stack has
been executed and verified successfully.