DFS Lab File Final
DFS Lab File Final
MCA-162 PAGE|1
PRACTICAL FILE
LINEAR SEARCH
ALGORITHM
The main motive of linear search is to traverse through each element until it finds the element which has
to be searched.
Step 1. Start
Step 2. Entering the size of Array:
scanf("%d",&size);
Step 3. Creating an Array
for(int i=0;i<size;i++)
scanf("%d",&Arr[i]);
Step 4. Asking if we want to find an element (Inside a loop)
cout<<"\nDo you want to search an element? (Y/N)";
cin>>Y;
Step 5. if yes, ask for element to be searched
printf("Enter Element to search:"); scanf("%d",&ele); setting position as -1 then
entering the loop to compare every component of array with the element
Step if element is found set pos to i+1 and exit the loop int
6. pos=-1;
Step
7. Page | 4
for(int i=0;i<size;i++)
if(Arr[i]==ele)
pos=i+1;
break;
Step otherwise print element with its position in the array else
9.
printf("%d found at position %d.",ele,pos);
OUTPUTS First
Output
If
Y
--Element is found
BINARY SEARCH
ALGORITHM
The main motive of binary search is to search if the middle element is the element needed then change
the range depending if the element is greater or smaller than the middle element of array.
Pre-requisites:
The array should be in Ascending order.
Step 1. Start
Step 2. Sorting the array using any sort
technique
Step 3. Enter the element to be searched
cin>>ele;
Step 4. Set low as 0, high as size-1 and
declare pos int low=0,high=size-
1,mid;
Step 5. Run the loop while the condition
high>=low is true while(high>=low)
Step 6. set mid as Pag
(high+lo e |
w)/2 7
mid=(lo
w+high)/
2;
Step 7. if arr[mid] is the element
then return mid
if(Arr[mid]==ele)
return mid;
Step 8. otherwise check if element is greater
than arr[mid] set low as high+1 else
if(ele>Arr[mid])
low=mid+1;
Step 9. otherwise check if element is less than
the arr[mid] set high as mid-1 else
if(ele<Arr[mid])
high=mid-1;
Step 10.
w
he
n
th
e
lo
op
ex
its
re
tu
rn
-1
re
tu
rn
-1;
Step 11. If res is -1
print
element
not found
if(res==-1)
cout<<"Element not found in the array.";
Step 12. otherwise
print the
element’
s
position
else
cout<<"Element found
at position "<<res+1; Step 13. exit
Page | 9
2. Sorting
SELECTION SORT
ALGORITHM
The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the
list and swaps it with the first element of the unsorted part. This process is repeated for the remaining
unsorted portion until the entire list is sorted.
Step 1. Start
Step 2. Starting the loop (Step 4 to 7) for(int
i=0;i<size;i++)
Step 3. Selecting the first element as smallest element and running internal loop (Step 5 to 6) pos=i;
sml=Arr[i];
for(int j=i;j<size;j++)
Step 4. if the current element in loop will be smaller than ‘sml’ then it will be chosen as ‘sml’ if(sml>Arr[j])
{
sml=Arr[j];
pos=j;
}
Step 5. storing smallest element’s position in temp and swapping it with Arr[i] i’th element of
Array temp=Arr[pos];
Arr[pos]=Arr[i];
Arr[i]=temp; Page | 10
Step 6. Print the sorted Array cout<<"\nSorted
Array:\n";
for(i=0;i<size;i++)
cout<<Arr[i]<<" ";
Step 7. end
PROGRAM
#include<iostream.h>
#include<conio.h>
int Arr[100]; // Global Array with maximum size as 100
void select_sort(int size) { cout<<"Array after each step:\n";
int temp,sml,pos;
for(int i=0;i<size;i++) {
pos=i;
sml=Arr[i];
for(int j=i;j<size;j++) {
if(sml>Arr[j])
{
sml=Arr[j];
pos=j;
}
}
temp=Arr[pos];
Arr[pos]=Arr[i];
Arr[i]=temp;
cout<<"\nStep"<<i+1<<": ";
for(j=0;j<size;j++)
cout<<Arr[j]<<" ";
}
cout<<"\nSorted Array:\n";
for(i=0;i<size;i++)
cout<<Arr[i]<<" ";
cout<<endl;
}
void main()
{
clrscr();
int size;
cout<<"Enter Size of Array:";
cin>>size;
cout<<"Enter Elements into the Array:\n";
for(int i=0;i<size;i++)
cin>>Arr[i];
select_sort(size);
getch();
}
Page | 11
OUTPUT
BUBBLE SORT
ALGORITHM
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements
if they are in the wrong order.
Step 1. Start
Step 2. Start the loop (Step 4 to 6) for(int
i=0;i<size-1;i++)
Step 3. Start Inner loop (Step 5 to 6) for(int
j=0;j<size-i-1;j++)
Step 4. Check if the next element in the Array is greater than the current element then swap it.
if(Arr[j]>Arr[j+1]) {
temp=Arr[j];
Arr[j]=Arr[j+1];
Arr[j+1]=temp;
}
Step 5. Print the sorted Array
for(j=0;j<size;j++)
cout<<Arr[j]<<" ";
Step 6. End
PROGRAM
//Header Files
#include<iostream.h>
#include<conio.h>
int Arr[50]; Page | 12
//Maximum Size for the Array is 50 void
bub_sort(int size) {
int temp;
for(int i=0;i<size-1;i++) {
for(int j=0;j<size-i-1;j++) {
if(Arr[j]>Arr[j+1]) {
temp=Arr[j];
Arr[j]=Arr[j+1];
Arr[j+1]=temp;
}
}
cout<<"Array after Step "<<i+1<<": ";
for(j=0;j<size;j++)
cout<<Arr[j]<<" ";
cout<<endl;
}
}
void main() {
clrscr();
int size;
cout<<"Enter Size of Array:";
cin>>size;
cout<<"Enter elements in the Array:\n"; for(int
i=0;i<size;i++)
cin>>Arr[i];
bub_sort(size);
getch();
}
OUTPUT
INSERTION SORT
ALGORITHM
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your
hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part
are picked and placed at the correct position in the sorted part.
Step 1. Start
Step 2. Start the loop (Step 4 to 8) Page | 13
for(i=1;i<size;i++)
Step 3. Store the current element in key & set j as i-1
key=Arr[i]; j=i-1;
Step 4. Start the Inner loop and run it till Arr[j] is greater than key (Step 6 to 7) while(j>=0
&& Arr[j]>key)
Step 5. Move each element 1 step ahead its position
Arr[j+1]=Arr[j];
j--;
Step 6. Storing key at j+1 position
Arr[j+1]=key;
Step 7. Print the sorted array
for(int k=0;k<size;k++)
cout<<Arr[k]<<" "; Step 8. End
PROGRAM
#include<iostream.h>
#include<conio.h> int
Arr[50]; void ISort(int
size) {
int key,i,j;
for(i=1;i<size;i++) {
key=Arr[i];
j=i-1;
while(j>=0 && Arr[j]>key) {
Arr[j+1]=Arr[j];
j--;
}
Arr[j+1]=key;
cout<<"Array after Step "<<i<<": ";
for(int k=0;k<size;k++)
cout<<Arr[k]<<" ";
cout<<endl;
}
}
void main() {
clrscr();
int size;
cout<<"Enter Size of Array:";
cin>>size;
cout<<"Enter Elements in Array:\n";
for(int i=0;i<size;i++)
cin>>Arr[i];
ISort(size);
getch();
}
OUTPUT Page | 14
QUICK SORT
ALGORITHM
QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an element as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct position
in the sorted array.
Step 1. Start
Step 2. Start sorting by sending the first and last position of the array to the function qsort(0,size-1);
Step 3. if low is less than high then find the pivot (sorted) position using partition function int
pi=part(low,high);
Step 4. send low, pi-1 and pi+1,high as first and last position to the sort function
qsort(low,pi-1); qsort(pi+1,high);
Step 5. part()
Step 6. Choose last element of the part of array as pivot and i as low-1
int pivot=Arr[high]; int i=(low-1);
Step 7. Start the loop and run it till it is less than high(Step 9 to ) for(int
j=low;j<=high-1;j++)
Step 8. if the current element will be less than pivot element increment i and swap A[i] and A[j]
if(Arr[j]<pivot)
{
i++;
swap(Arr[i],Arr[j]);
}
Step 9. Swap a[i+1] with a[high] swap(Arr[i+1],Arr[high]);
Step 10. Print the sorted
Array for(int i=0;i<size;i++)
cout<<Arr[i]<<" "; Step 11.
End
PROGRAM
#include<iostream.h>
#include<conio.h>
int size; int
Arr[100];
void swap(int &a,int &b) { Page | 15 int temp; temp=a; a=b;
b=temp;
}
void disp() {
for(int i=0;i<size;i++)
cout<<Arr[i]<<" ";
cout<<endl;
}
int part(int low,int high) {
int pivot=Arr[high];
int i=(low-1);
for(int j=low;j<=high-1;j++) {
if(Arr[j]<pivot) {
i++;
swap(Arr[i],Arr[j]);
}
}
swap(Arr[i+1],Arr[high]);
return (i+1);
}
OUTPUT
Page | 16
MERGE SORT
ALGORITHM
Merge sort is defined as a sorting algorithm that works by dividing an array into smaller subarrays,
sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array.
Step 1. Start
Step 2. Declare array, left, right and mid variable
Step 3. Perform Merge Function
if (left > right); else
{
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
}
Step 4. End
PROGRAM
#include<iostream.h>
#include<conio.h>
int size;
int arr[100];
void print() {
for(int i=0;i<size;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void merge(int left,int mid,int right) {
int Lsize=mid-left+1;
int Rsize=right-mid;
int *Larr= new int[Lsize];
int *Rarr= new int[Rsize];
for(int i=0;i<Lsize;i++)
Larr[i]=arr[left+i];
for(int j=0;j<Rsize;j++) Page | 17
Rarr[j]=arr[mid+1+j];
int IndexLarr=0;
int IndexRarr=0;
int IndexMarr=left;
while(IndexLarr<Lsize && IndexRarr<Rsize)
{ if(Larr[IndexLarr]<=Rarr[IndexRarr])
{
arr[IndexMarr]=Larr[IndexLarr];
IndexLarr++;
}
else
{
arr[IndexMarr]=Rarr[IndexRarr];
IndexRarr++;
}
IndexMarr++;
}
while(IndexLarr<Lsize)
{
arr[IndexMarr]=Larr[IndexLarr];
IndexLarr++;
IndexMarr++;
}
while(IndexRarr<Rsize)
{
arr[IndexMarr]=Rarr[IndexRarr];
IndexRarr++;
IndexMarr++;
}
delete[] Larr;
delete[] Rarr;
}
void mergesort(int begin,int end) {
if(begin>=end);
else {
int mid=begin+(end-begin)/2;
mergesort(begin,mid);
mergesort(mid+1,end);
merge(begin,mid,end);
}
}
void main() {
clrscr();
cout<<"Enter Size of the Array:";
cin>>size;
b. Display/ Traversal
Step 1. Start
Step 2. Create a temporary node
LinkedList *ptr=new LinkedList;
Step 3. Store the first node in a temporary pointer variable. ptr=first;
Step 4. Compare if first node is NULL if(first==NULL)
cout<<"Empty List.";
Step 5. if ptr(temporary variable is not NULL)
Start the loop. while(ptr!=NULL)
{
cout<<ptr->data;
if(ptr->next!=NULL)
cout<<" --> ";
ptr=ptr->next;
}
Step 6. end;
c. Insertion at Beginning
Step 1. Start
Step 2. Create a temporary node
LinkedList *n=new LinkedList;
Step 3. Store the entered data in its information field and set its next link to first n
-> data= item; n->next=first;
Step 4. Make the temporary node as first node (Change the first node)
first=n; Step 5. end
d. Insertion at End
Step 1. Start
Step 2. Create a temporary node
LinkedList *n=new LinkedList;
Step 3. Store the entered data in its information field and set its next link to NULL n -
> data= item;
n->next=NULL;
Step 4. Check if first is NULL and set the temporary node as first if the condition is true.
if(first==NULL)
first=n;
Otherwise traverse to the last node and add the new node to the end else
Step 5.
Page | 20
LinkedList *ptr=first;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=n;
Step 6. End
Step 3. Create a node and store the item to be inserted in its data
LinkedList *n= new LinkedList; n->data=item;
Step 4. Create a node and store the item to be inserted in its data and set next as
NULL
LinkedList *n= new LinkedList;
n->data=item; n->next=NULL;
Step 5. Create 2 temporary nodes one to traverse and one to store previous node
LinkedList *ptr=first;
LinkedList *prev=first;
Step 6. Check if first is NULL and pos is 1 if(first==NULL
&& pos==1)
first=n; Page | 21
Step 7. check if var is not pos AND ptr is not NULL and run the loop while(var!=pos
&& ptr!=NULL)
prev=ptr;
ptr=ptr->next; var++;
Step 8. check if ptr is NULL and var is pos if(ptr==NULL
&& var==pos)
prev->next=n;
n->next=NULL;
Step 9. otherwise check if ptr is not NULL else
if(ptr!=NULL)
n->next=prev->next;
prev->next=n;
Step 10. otherwise display POSITION NOT FOUND else
cout<<"Position NOT found!\n"; Step 11. end
Step 6. if ptr-> data is ele set f=1 and break out of the loop if(ptr-
>data==ele)
f=1;
break;
Step 7. otherwise increment the pos and send ptr to its next link
else
pos++;
ptr=ptr->next;
Step 8. if f is 1 print element found
if(f==1)
cout<<ele<<" found at "<<pos<<endl;
Step 9. otherwise print not found else
cout<<"NOT FOUND!";
PROGRAM SLL.CPP
//INCLUDING ALL NECESSARY HEADER FILES
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
OUTPUTS
Main function start
Page | 30
Page | 31
8 Searching
-- When element is found
9 Exit
4. Doubly Linked List
ALGORITHMS
a. Creation of the Linked List / Definition Page | 33 struct DLL {
//Definition
int data; //Information
DLL *prev; //Pointer to previous node
DLL *next; //Pointer to next node
} *first; //first node of the Linked List
b. Display/ Traversal
Step 1. Start
Step 2. Compare if first node is NULL if(first==NULL)
cout<<"Empty List.";
Step 3. Otherwise, Create a temporary node
DLL *ptr=new DLL;
Step 4. Store the first node in a temporary pointer variable. ptr=first;
Step 5. if ptr(temporary variable is not NULL) Start
the loop.
while(ptr!=NULL)
cout<<ptr->data;
if(ptr->next!=NULL)
cout<<" <--> ";
ptr=ptr->next;
Step 6. end;
c. Insertion at Beginning
Step 1. Start
Step 2. Create a temporary node
DLL *n=new DLL;
Step 3. Store the entered data in its information field and set its next link and
previous link to NULL n->data=item; n->prev=NULL; n->next=NULL;
Step 4. Make the temporary node as first node if first is NULL.
if(first==NULL) first=n;
Step 5. Otherwise, Set n’s next link to first and first’s previous link to n the make n the first
node
else
n->next=first; first-
>prev=n; first=n;
ptr->next->prev=n;
ptr->next=n;
n->prev=ptr;
Step 1. End
Page | 34
1. Insert at a Particular Position
Step 1. Start
Step 2. set variables to compare the position (var=1)
Step 3. Insert the position at which you want to insert cin>>pos;
Step 8. check if var is not pos AND ptr is not NULL and run the loop (traverse)
while(ptr!=NULL && var!=pos)
prevs=ptr;
ptr=ptr->next; var++;
Step 9. check if ptr is NULL and var is pos set prevs->next to n and n->prev to prevs
if(ptr==NULL && var==pos)
prevs->next=n; n-
>prev=prevs;
Step 10. otherwise check if ptr is not NULL set previous and next link accordingly. else
if(ptr!=NULL)
n->next=prevs->next; prevs->next-
>prev=n; prevs->next=n;
n->prev=prevs;
Step 11. otherwise display POSITION NOT FOUND else
cout<<"Position NOT found!\n"; Step 12. end
Page | 36
Step 8. set ptr->prev->next to ptr->next ptr->prev->next=ptr->next;
Step 9. check if ptr’s next link is not NULL if(ptr->next!=NULL)
ptr->next->prev=ptr->prev;
Step 6. if var is not pos and ptr is not NULL increment the steps
while(ptr->next!=NULL && var!=pos)
ptr=ptr->next; var++;
Step 7. if ptr->next is NULL and var is pos set ptr->prev->next to NULL if(ptr-
>next==NULL && var==pos)
cout<<"Deleted Value:"<<ptr->data<<endl; ptr->prev-
>next=NULL;
Step 8. otherwise check if ptr is not NULL and var is pos set links accordingly
else if(ptr!=NULL && var==pos)
ptr->prev->next=ptr->next; if(ptr->next!
=NULL && pos!=1)
cout<<"Deleted Value:"<<ptr->data<<endl;
ptr->next->prev=ptr->prev;
Step 9. Otherwise, display position not found else
cout<<"Position NOT found.\n";
Step 7. otherwise increment the pos and send ptr to its next link
else pos++; ptr=ptr->next;
PROGRAM DLL.CPP
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
//Creation of the Linked List
struct DLL { int
data; DLL *prev;
DLL *next;
};
DLL *first;
//Display or Traversal void
display() {
if(first==NULL)
cout<<"Empty List."; else {
DLL *ptr=new DLL;
ptr=first; while(ptr!
=NULL) { cout<<ptr->data;
if(ptr->next!=NULL)
cout<<" <--> ";
ptr=ptr->next;
}
} Page | 38
getch();
}
//Insertion at the beginning void
Insertb() {
int item;
cout<<"Enter the Element you want to insert:";
cin>>item;
DLL *n=new DLL;
n->data=item;
n->prev=NULL;
n->next=NULL;
if(first==NULL)
first=n;
else {
n->next=first;
first->prev=n;
first=n;
}
display();
}
//Insertion at the end void
Inserte() {
int item;
cout<<"Enter the Element you want to insert:";
cin>>item; DLL *n=new DLL; n-
>data=item; n->prev=NULL; n->next=NULL;
if(first==NULL)
first=n;
else {
DLL *ptr=first;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=n; n-
>prev=ptr;
}
display();
}
//Insertion at any position
void Inserta() {
int item;
DLL *n=new DLL;
cout<<"Enter element to be inserted:";
cin>>item; n->data=item;
n->next=NULL; Page | 39
n->prev=NULL;
clrscr();
int ch2;
cout<<"1. Insert at Particular Position.\n";
cout<<"2. Insert after Particular Element.\n";
cout<<"Enter Choice:\n";
cin>>ch2;
if(ch2==1) {
int pos,var=1;
cout<<"Enter Position:";
cin>>pos;
DLL *prevs = new DLL;
if(first==NULL)
first=n;
else {
DLL *ptr=first;
if(first==NULL && pos==1)
first=n;
if(pos==1) {
first->prev=n;
n->next=first;
first=n;
}
while(ptr!=NULL && var!=pos) {
prevs=ptr;
ptr=ptr->next;
var++;
}
if(ptr==NULL && var==pos) {
prevs->next=n;
n->prev=prevs;
}
else if(ptr!=NULL) {
n->next=prevs->next;
prevs->next->prev=n; prevs-
>next=n; n->prev=prevs;
}
else
cout<<"Position NOT found.";
}
}
if(ch2==2) {
int ele;
cout<<"Enter Element:";
cin>>ele;
if(first==NULL)
first=n; Page | 40 else {
DLL *ptr=first;
while(ptr!=NULL && ptr->data!=ele) {
ptr=ptr->next;
}
if(ptr==NULL)
cout<<"Element NOT found\n";
else {
n->next=ptr->next;
ptr->next->prev=n;
ptr->next=n;
n->prev=ptr;
}
}
}
display();
}
//Delete from beginning void
Delb() {
if(first==NULL);
else if(first->next==NULL) {
cout<<"Deleted Element:"<<first->data<<endl;
first=NULL;
}
else {
cout<<"Deleted Element:"<<first->data<<endl;
first=first->next;
first->prev=NULL;
}
display();
}
//Delete from end void Dele()
{ if(first==NULL); else if(first-
>next==NULL) {
cout<<"Deleted Element:"<<first->data<<endl;
first=NULL;
}
else {
DLL *ptr=first;
while(ptr->next!=NULL) ptr=ptr-
>next; cout<<"Deleted
Element:"<<ptr->data<<endl; ptr-
>prev->next=NULL;
}
display();
}
//Delete from any position Page | 41 void Dela() { clrscr(); int ch2;
cout<<"1. Delete from Particular Position.\n";
cout<<"2. Delete a Particular Element.\n";
cout<<"Enter Choice:\n";
cin>>ch2;
if(ch2==1) {
int pos,var=1;
cout<<"Enter Position:";
cin>>pos;
DLL *ptr=first;
if(first->next==NULL && pos==1) {
cout<<"Deleted Value:"<<first->data<<endl;
first=NULL;
}
if(pos==1) {
cout<<"Deleted Value:"<<first->data<<endl;
first=first->next;
first->prev=NULL;
}
while(ptr->next!=NULL && var!=pos) {
ptr=ptr->next;
var++;
}
if(ptr->next==NULL && var==pos) {
cout<<"Deleted Value:"<<ptr->data<<endl;
ptr->prev->next=NULL;
}
else if(ptr!=NULL && var==pos) {
ptr->prev->next=ptr->next; if(ptr->next!=NULL
&& pos!=1) cout<<"Deleted Value:"<<ptr-
>data<<endl;
ptr->next->prev=ptr->prev;
}
else
cout<<"Position NOT found.\n";
}
if(ch2==2) {
int ele;
cout<<"Enter Element:"; cin>>ele;
DLL *ptr=first;
if(first->next==NULL && first->data==ele)
first=NULL;
else if(first->data==ele) {
first=first->next; first->prev=NULL;
Page | 42
}
else {
ptr=ptr->next;
ptr->prev->next=ptr->next;
if(ptr->next!=NULL)
ptr->next->prev=ptr->prev;
}
}
display();
}
//Searching the Element
void Srch() {
int ele,pos=1,f=0;
cout<<"Enter element you want to search:";
cin>>ele;
DLL *ptr=first; while(ptr!
=NULL) {
if(ele==ptr->data) {
f=1;
break;
}
else {
ptr=ptr->next;
pos++;
}
}
if(f==1)
cout<<ele<<" found at "<<pos<<endl;
else
cout<<"Element not found!"<<endl;
getch();
}
//main function / driver of the program
void main() {
int ch;
while(1) {
clrscr();
cout<<"\nDOUBLY LINK LIST MENU\n";
cout<<"1. Display\n";
cout<<"2. Insert in the beginning\n";
cout<<"3. Insert at the end\n";
cout<<"4. Insert at any position\n";
cout<<"5. Delete from the beginning\n";
cout<<"6. Delete from the end\n"; Page | 43 cout<<"7. Delete from any
position\n";
cout<<"8. Searching\n"; cout<<"9. Exit.\n";
cout<<"Enter your choice:\n";
cin>>ch;
switch(ch) {
case 1: display();
break;
case 2: Insertb();
break;
case 3: Inserte();
break;
case 4: Inserta();
break;
case 5: Delb();
break;
case 6: Dele();
break;
case 7: Dela();
break;
case 8: Srch();
break;
case 9: exit(0);
break;
default: cout<<"Wrong Choice!";
getch();
}
}
}
OUTPUTS-
1. First Screen
4. Display/ Traversal
Page | 45
-- If element is found
Page | 46
10. Exit
Exiting show this screen
5. Circular Singly Linked List
ALGORITHMS
//Definition of Linked List node
Page | 47
struct node {
int data;
struct node *next;
};
struct node *head;
//Display/Traversal
//Insertion at Beginning
Step 1. if ptr = null
write overflow go
to step 11 [end of
if]
Step 2. set new_node = ptr
Step 3. set ptr = ptr -> next
Step 4. set new_node -> data = val
Step 5. set temp = head
Step 6. repeat step 7 while temp -> next != head
Step 7. set temp = temp -> next [end
of loop]
Step 8. set new_node -> next = head
Step 9. set temp → next = new_node
Step 10. set head = new_node
Step 11. exit
//Insertion at End
Step 1. if ptr = null write
overflow
go to step 10
[end of if]
Step 2. set new_node = ptr
Step 3. set ptr = ptr -> next
[end of loop]
t
So
t
7
e
p
u
7
. n
t
i
l
p
t
r
-
>
n
e
x
t
!
=
h
e
a
d
i
f
p
t
r
d
a
t
a
i
t
e
m
w
r
i
t
e
i
+
1
r
e
t
u
r
n
[
e
n
d
o
f
i
f
]
Sp
t
e
p
8
.
S exit
t
e
p
9
.
# # main function contains the menu by which we call the above modules. # #
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
//STRUCTURE OF A NODE
struct node {
int data;
struct node *next;
};
struct node *head;
//INSERTION AT BEGINNING
void insertb() { struct
node *ptr,*temp; int
item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
printf("\nOVERFLOW");
else {
printf("\nEnter element value:");
scanf("%d",&item); ptr -> data
= item; if(head == NULL) {
head = ptr;
ptr -> next = head;
}
else {
temp = head;
while(temp->next != head)
temp = temp->next; ptr-
>next = head; temp ->
next = ptr;
head = ptr;
}
printf("\nNode inserted\n");
} }
//INSERTION AT END
void inserte() {
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
printf("\nOVERFLOW\n");
else { Page | 50 printf("\nEnter the element value:"); scanf("%d",&item); ptr->data =
item;
if(head == NULL)
{ head = ptr;
ptr -> next = head;
}
else {
temp = head;
while(temp -> next != head)
temp = temp -> next; temp -
> next = ptr;
ptr -> next = head;
}
printf("\nNode inserted\n");
}
}
//DELETION FROM BEGINNING
void delb() {
struct node *ptr;
if(head == NULL)
printf("\nUNDERFLOW");
else if(head->next == head) {
head = NULL;
free(head);
printf("\nNode deleted\n");
}
else
{ ptr =
head;
while(ptr -> next != head)
ptr = ptr -> next; ptr-
>next = head->next;
free(head);
head = ptr->next;
printf("\nNode deleted\n");
}
}
//DELETION FROM END void
dele() {
struct node *ptr, *preptr;
if(head==NULL)
printf("\nUNDERFLOW");
else if (head ->next == head) {
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else { Page | 51 ptr = head;
while(ptr ->next != head)
{ preptr=ptr;
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("\nnode deleted\n");
}
}
//TRAVERSAL/DISPLAY OF THE LINK LIST
void display()
{ struct
node *ptr;
ptr=head; if(head
== NULL)
printf("\nNothing to print");
else {
printf("\nList:");
while(ptr -> next != head)
{ printf("%d ->", ptr -> data);
ptr = ptr -> next;
}
printf("%d\n", ptr -> data);
}
}
//SEARCHING AN ELEMENT
void search()
{ struct node
*ptr; int
item,i=0,flag=1;
ptr = head; if(ptr
== NULL)
printf("\nEmpty List\n");
else {
printf("\nEnter item which you want to search?\n");
scanf("%d",&item); if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else {
while (ptr->next != head)
{ if(ptr->data == item)
{ printf("item found at location
%d ",i+1); flag=0; break;
}
else
flag=1; Page | 52
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
printf("Item not found\n");
}
}
//DRIVER PROGRAM
void main () {
clrscr(); int choice =0;
while(choice != 7) { printf("\
nMAIN MENU"); printf("\n1.Insert
in beginning\n printf(“2.Insert at end\
n”); printf(“3.Delete from Beginning\n”);
printf(“4.Delete from end\n”);
printf(“5.Search for an element\n”);
printf(“6.Display\n”); printf(“7.Exit\n");
printf("\nEnter your choice:\n");
scanf("\n%d",&choice); switch(choice)
{
case 1: insertb();
break; case 2:
inserte();
break;
case 3: delb();
break; case 4:
dele();
break; case 5:
search();
break; case 6:
display();
break;
case 7: exit(0);
default:
printf("Please enter valid choice..");
}
}
}
OUTPUTS:
Page | 53
6. Circular Doubly Linked List
ALGORITHMS
//Definition of Linked List node
Page | 54
struct node { struct node *prev; struct node *next;
int data;
};
//Insertion at Beginning
Step 1. if ptr = null write
overflow go to
step 13 [end
of if]
Step 2. set new_node = ptr
Step 3. set ptr = ptr -> next
Step 4. set new_node -> data = val
Step 5. set temp = head
Step 6. repeat step 7 while temp -> next != head
Step 7. set temp = temp -> next [end
of loop]
Step 8. set temp -> next = new_node
Step 9. set new_node -> prev = temp
Step 10. set new_node -> next = head
Step 11. set head -> prev = new_node
Step 12. set head = new_node
Step 13. exit
//Insertion at End
write underflow
go to step 8
[end of loop]
Step 9. exit
write underflow
go to step 8
[end of if]
[end of loop]
Step 8. exit
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
//DEFINITION OF A NODE
struct node {
struct node *prev;
struct node *next;
int data;
}*head;
//INSERTION AT BEGINNING
void insertb() { struct
node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL) printf("\nOVERFLOW"); else
{
printf("Enter Item value:");
scanf("%d",&item);
ptr->data=item;
if(head==NULL) {
head = ptr;
ptr -> next = head; Page | 56 ptr -> prev = head;
}
else { temp =
head; while(temp -> next != head)
temp = temp -> next;
temp -> next = ptr;
ptr -> prev = temp; head
-> prev = ptr; ptr -> next =
head;
head = ptr;
}
printf("Node inserted\n");
}
}
//INSERTION AT END void
inserte() { struct
node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL) printf("\nOVERFLOW"); else
{
printf("Enter Item value:");
scanf("%d",&item); ptr->data=item;
if(head == NULL)
{ head = ptr; ptr -> next
= head; ptr -> prev =
head;
}
else {
temp = head;
while(temp->next !=head) {
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
head -> prev = ptr;
ptr -> next = head;
}
}
printf("Node inserted\n");
}
//DELETION FROM BEGINNING void
delb() {
struct node *temp;
if(head == NULL) Page | 57 printf("\n UNDERFLOW");
else if(head->next == head) {
head = NULL;
free(head);
printf("Node deleted\n");
}
else {
temp = head;
while(temp -> next != head)
temp = temp -> next;
temp -> next = head -> next;
head -> next -> prev = temp;
free(head);
head = temp -> next;
printf("Node deleted\n");
}
}
//DELETION FROM END void
dele() {
struct node *ptr;
if(head == NULL)
printf("\n UNDERFLOW");
else if(head->next == head) {
head = NULL;
free(head);
printf("Node deleted\n");
}
else {
ptr = head;
if(ptr->next != head)
ptr = ptr -> next;
ptr -> prev -> next = head;
head -> prev = ptr -> prev;
free(ptr);
printf("Node deleted\n");
}
}
//TRAVERSAL/DISPLAY
void display()
{ struct
node *ptr;
ptr=head; if(head
== NULL)
printf("Nothing to
print");
else {
printf("List:\n");
while(ptr -> next != head) {
printf("%d ->", ptr -> data);
ptr = ptr -> next; Page | 58
}
printf("%d\n", ptr -> data);
}
}
//SEARCHING AN ELEMENT
void search() {
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
printf("Empty List\n");
else {
printf("Enter item which you want to search?\n");
scanf("%d",&item);
if(head ->data == item) {
printf("Item found at location %d\n",i+1);
flag=0;
}
else {
while (ptr->next != head) { if(ptr->data == item)
{ printf("Item found at location %d\n",i+1);
flag=0;
break;
}
else
flag=1;
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
printf("Item not found.\n");
}
}
//DRIVER FUNCTION
void main() {
clrscr();
printf("\nMain Menu\n");
printf("Choose one option:\n");
printf("1.Insert at Beginning\n");
printf("2.Insert at end\n");
printf("3.Delete from Beginning\n");
printf("4.Delete from end\n");
printf("5.Search\n"); printf("6.Display\
n"); printf("7.Exit\n");
int choice =0; Page | 59 while(choice != 9) { printf("Enter your choice:\n"); scanf("%d",&choice);
switch(choice)
{
case 1: insertb();
break;
case 2: inserte();
break;
case 3: delb();
break;
case 4: dele();
break;
case 5: search();
break;
case 6: display();
break;
case 7: exit(0);
default: printf("Please enter valid choice..");
}
}
}
OUTPUTS:
7. Stack
Page | 60
Stack is a LIFO structure, i.e., Last In First Out Structure, the element inserted latest will be deleted first,
just like a pile or stack of plates at a wedding hall.
USING ARRAY
ALGORITHMS
//Peek
Step 1. Begin
Step 2. if top = -1 then stack empty
Step 3. item = stack[top]
Step 4. return item
Step 5. End
PROGRAM
#include<iostream.h>
#include<conio.h> #include<stdlib.h>
int size=0; //Maximum Size of Array to be input by user int
S[100]; //Max size possible is 100 int top=-1; void display()
{ for(int i =top;i>=0;i--)
cout<<S[i]<<endl;
}
void push() {
int ele;
cout<<"Enter
element to
input/push:";
cin>>ele;
if(top==size-1)
cout<<"Stack Overflowed.";
else {
++top; Page | 61
S[top]=ele;
}
}
void pop() {
if(top==-1)
cout<<"Stack Underflowed.";
else {
cout<<"Popped Element:"<<S[top];
top--;
}
}
void peek() {
if(top==-1)
cout<<"Underflow"<<endl;
else
cout<<S[top];
}
void isEmpty() {
if(top==-1)
cout<<"Empty!";
else
cout<<"Not Empty.";
}
void isFull() {
if(top==size-1)
cout<<"Full!";
else
cout<<"Not Full.";
}
void main() {
clrscr();
cout<<"Enter Size of the Stack:";
cin>>size; int ch;
cout<<"MENU"<<endl;
cout<<"1. Push into the Stack"<<endl;
cout<<"2. Pop from Stack"<<endl;
cout<<"3. Peek the Stack"<<endl;
cout<<"4. Check if the stack is empty?"<<endl;
cout<<"5. Check if the stack is full?"<<endl;
cout<<"6. Display the Stack"<<endl;
cout<<"7. Exit the program."<<endl;
while(1) {
cout<<endl<<"Choose your option:";
cin>>ch;
switch(ch) {
case 1: push();
break; Page | 62 case 2: pop(); break; case 3: peek();
break;
case 4: isEmpty();
break;
case 5: isFull();
break;
case 6: display();
break;
case 7: exit(0);
default: cout<<"Wrong Choice.\nChoose Again!";
}
}
}
OUTPUTS:
//Starting Screen
//Push
//Peek
//Pop
Page | 63
//isEmpty?
//isFull?
//Structure of a Node
struct S {
int data;
S *next;
};
//Push Operation
Step 1. Initialise a node
Step 2. Update the value of that node by data i.e. node->data = data
Step 3. Now link this node to the top of the linked list Step
4. And update top pointer to the current node
//Pop Operation
Step 1. First Check whether there is any node present in the linked list or not, if not then return
Step 2. Otherwise make pointer let say temp to the top node and move forward the top node by
1 step
Step 3. Now free this temp node
//Peek Operation
Step 1. Check if there is any node present or not, if not then return.
Step 2. Otherwise return the value of top node of the linked list
//Display Operation
Step 1. Take a temp node and initialize it with top pointer
Step 2. Now start traversing temp till it encounters NULL Step
3. Simultaneously print the value of the temp node
PROGRAM
#include<iostream.h>
#include<conio.h> #include<stdlib.h>
int size; //Max size of Stack to be input by user
struct S { //Stack Linked List int data;
S *next; Page | 64
};
S *top=NULL;
int Ssize=0;
void display() {
if(top==NULL)
cout<<"Empty Stack."<<endl;
else {
S *temp=top;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
}
void push() {
S *temp=new S();
cout<<"Enter element to insert:";
cin>>temp->data; temp-
>next=NULL; if(Ssize==size)
cout<<"Stack Overflowed.";
else {
temp->next=top;
top=temp;
Ssize++;
}
}
void pop() {
if(top==NULL)
cout<<"Stack Underflowed";
else {
cout<<"Popped Element:"<<top->data;
top=top->next;
Ssize--;
}
}
void peek() {
if(top==NULL)
cout<<"Underflow"<<endl;
else
cout<<"Top="<<top->data;
}
void isEmpty() {
if(top==NULL)
cout<<"Empty!"; else
cout<<"Not Empty."; Page | 65
}
void isFull() {
if(Ssize==size)
cout<<"Full!";
else
cout<<"Not Full.";
}
void main() {
clrscr();
cout<<"Enter Size of the Stack:";
cin>>size; int ch;
cout<<"MENU"<<endl;
cout<<"1. Push into the Stack"<<endl;
cout<<"2. Pop from Stack"<<endl;
cout<<"3. Peek the Stack"<<endl;
cout<<"4. Check if the stack is empty?"<<endl;
cout<<"5. Check if the stack is full?"<<endl;
cout<<"6. Display the Stack"<<endl;
cout<<"7. Exit the program."<<endl;
while(1) {
cout<<endl<<"Choose your option:";
cin>>ch;
switch(ch) {
case 1: push();
break;
case 2: pop();
break;
case 3: peek();
break;
case 4: isEmpty();
break;
case 5: isFull();
break;
case 6: display();
break;
case 7: exit(0);
default: cout<<"Wrong Choice.\nChoose Again!";
}
}
}
OUTPUTS:
Page | 66
//Push
//Display
//Pop
8. Queue
Queue is a FIFO structure, i.e., First In First Out Structure, the element inserted first will be deleted first,
just like a queue of people at ticket counter.
Page | 67
USING ARRAY
ALGORITHMS
//INSERTION INTO ARRAY
Step 1. if rear = max - 1 write
overflow go to
step
[end of if]
Step 2. if front = -1 and rear = -1
set front = rear = 0 else
set rear = rear + 1
[end of if]
Step 3. set queue[rear] = num
Step 4. exit
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define maxsize 5 int
front = -1, rear = -1;
int queue[maxsize];
void insert() {
int item;
printf("Enter the Element:");
scanf("%d",&item);
if(rear == maxsize-1) {
printf("\nOVERFLOW");
return;
}
if(front == -1 && rear == -1) {
front = 0;
rear = 0;
}
else
rear = rear+1;
queue[rear] = item; Page | 68 printf("\nValue Inserted ");
}
void del() {
int item;
if (front == -1 || front > rear) {
printf("UNDERFLOW\n");
return;
}
else {
if(front == rear) front = - {
1;
rear = -1 ;
}
else
front = front + 1;
printf("\nValue Deleted ");
}
}
void display() {
int i;
if(rear == -1)
printf("\nEmpty Queue\n");
else {
printf("List:\n");
for(i=front;i<=rear;i++) {
printf("%d\n",queue[i]);
}
}
}
void main () {
clrscr();
printf("\nMain Menu"); printf("\
n1.Insert an element\n");
printf("2.Delete an element\n");
printf("3.Display the queue\n");
printf("4.Exit");
int choice; while(choice != 4)
{ printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice) {
case 1: insert();
break;
case 2: del();
break;
case 3: display();
break;
case 4: exit(0); Page | 69 default: printf("\nEnter valid choice:\n");
}
}
}
OUTPUT:
PROGRAM
#include<stdio.h>
#include<stdlib.h> #include<conio.h>
struct node {
int data;
struct node *next;
};
struct node *front, *rear;
void insert() {
struct node *ptr;
int item;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW\n");
return;
}
else { printf("Enter
value:");
scanf("%d",&item);
ptr -> data = item;
if(front == NULL) {
front = ptr; rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else {
rear -> next = ptr; rear =
ptr;
rear->next = NULL;
}
}
}
void del() {
struct node *ptr;
if(front == NULL) {
printf("\nUNDERFLOW\n");
return;
}
else {
ptr = front; Page | 71 front = front -> next; free(ptr);
}
}
void display()
{ struct
node *ptr; ptr =
front;
if(front == NULL)
printf("\nEmpty queue\n"); else {
printf("List:");
while(ptr != NULL) {
printf("%d ",ptr -> data);
ptr = ptr -> next;
}
printf("\n");
}
}
void main () {
clrscr();
int choice;
printf("\nMain Menu\n"); printf("\
n1.Insert an element\n"); printf("2.Delete
an element\n"); printf("3.Display the
queue\n");
printf("4.Exit\n");
while(choice != 4)
{
printf("Enter your choice:");
scanf("%d",& choice);
switch(choice) {
case 1:insert();
break;
case 2:del();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("\nEnter valid choice??\n");
}
}
}
OUTPUT:
Page | 72
CIRCULAR QUEUE USING ARRAY
ALGORITHMS:
Insertion():
Step 1. if (rear+1)%max = front
write " overflow " goto
step 4
[end of if]
Step 2. if front = -1 and rear = -1 set front =
rear = 0 else if rear = max - 1 and
front ! = 0 set rear = 0 else
set rear = (rear + 1) % max
[end of if]
Step 3. set queue[rear] = val
Step 4. exit
deletion():
Step 1. if front = -1 write "
underflow " goto
step 4
[end of if]
Step 2. set val = queue[front]
Step 3. if front = rear set front
= rear = -1 else
if front = max -1
set front = 0 else
set front = front + 1
[end of if]
[end of if]
Step 4. exit
PROGRAM
#include <stdlib.h>
#include <stdio.h>
int front=-1; Page | 73 int rear=-1; int arr[10]; void enque(); void deque(); void printque();
void main() {
int choice;
while(1) {
printf("\n1.To enter an element in the queue");
printf("\n2.To delete an element from the queue");
printf("\n3.To print the queue");
printf("\n4.Exit\n");
scanf("%d",&choice);
switch(choice) {
case 1:enque();
break; case
2:deque();
break; case
3:printque();
break;
case 4:exit(1);
default:printf("\nincorrect choice");
}
}
}
void enque() { if((rear+1)%10==front)
printf("\nQueue is full");
else { int item; printf("\nEnter the item :
"); scanf("%d",&item);
if(front==-1 && rear==-1) {
front++; rear++;
arr[rear]=item;
} else
{ rear=(rear+1)%10;
arr[rear]=item;
}
} }
void deque() { if(front ==-1 &&
rear==-1)
printf("\nStack is empty");
else { if(front==rear)
{
printf("\nThe item you deleted is :%d",arr[front]); Page | 74 rear=-1;
front=-1;
}
else { printf("\nThe item you deleted is :%d",arr[front]);
front=(front +1)%10;
}
}
}
void printque() {
int i; printf("\n");
printf("\nThe Queue is :"); if(front==-1
&& rear ==-1)
printf("\nempty");
else { if(rear>=front)
{ for(i=front;i<=rear;i++)
printf("%d ",arr[i]);
}
else { for(i=front;i<10;i++)
printf("%d ",arr[i]);
for(i=0;i<=rear;i++) printf("%d
",arr[i]);
}
}
}
OUTPUT:
Page | 75
9. File Handling
getc() and putc():
PROGRAM
#include<stdio.h> Page | 76
int main()
{
FILE *fp; char ch; fp =
fopen("file.txt", "w"); if
(fp == NULL)
{ printf("Error opening file\n");
return 1;
}
printf("Enter some text (press Ctrl+Z to end):\n"); while
((ch = getchar()) != EOF)
{ putc(ch, fp);
}
fclose(fp); fp =
fopen("file.txt", "r"); if
(fp == NULL)
{ printf("Error opening file\n");
return 1;
}
printf("The content of the file is:\n"); while
((ch = getc(fp)) != EOF)
{
putchar(ch);
}
fclose(fp);
return 0;
}
OUTPUT:
fprintf()
PROGRAM
#include<stdio.h> void
main()
{
FILE *fptr;
int id;
char name[30]; float
salary;
fptr = fopen("emp.txt", "w+"); Page | 77 if (fptr == NULL)
{ printf("File does not exists \n");
return;
}
printf("Enter the id\n"); scanf("%d",
&id); fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name); fprintf(fptr,
"Name= %s\n", name); printf("Enter
the salary\n"); scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
OUTPUT:
fscanf()
PROGRAM
#include<stdio.h>
void main()
{
FILE *fp; char buff[255]; fp =
fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF)
printf("%s ", buff );
fclose(fp);
}
OUTPUT:
10. Tree
Binary Search Tree
INSERTION Page | 78
ALGORITHM
Step 1. Search the key to be inserted from the root node till some leaf node is reached. Step
2. Once a leaf node is reached, insert the key as child of that leaf node.
PROGRAM
#include<stdio.h>
#include<stdlib.h> struct
Node { struct Node
*lchild; int data;
struct Node *rchild;
} *root = NULL;
void Inorder(struct Node *p) { if
(p) {
Inorder(p->lchild); printf("%d
", p->data); Inorder(p-
>rchild);
}
}
struct Node *RInsert(struct Node *p, int key) {
struct Node *t = NULL; if (p == NULL) { t = (struct
Node *)malloc(sizeof(struct Node)); t->data =
key;
t->lchild = t->rchild = NULL;
return t;
} if (key < p->data) p->lchild =
RInsert(p->lchild, key); else if (key > p->data)
p->rchild = RInsert(p->rchild, key); return
p;
}
int Height(struct Node *p) {
int x, y; if (p ==
NULL) return 0; x =
Height(p->lchild); y =
Height(p->rchild);
return x > y ? x + 1 : y + 1;
}
struct Node *InPre(struct Node *p) {
while (p && p->rchild != NULL)
p = p->rchild;
return p;
}
struct Node *InSucc(struct Node *p) {
while (p && p->lchild != NULL) Page | 79 p = p->lchild;
return p;
}
int main() { struct Node
*temp; root =
RInsert(root, 50);
RInsert(root, 10);
RInsert(root, 40);
RInsert(root, 20);
RInsert(root, 30);
Inorder(root);
return 0; }
OUTPUT:
DELETION
ALGORITHM
For node with child
• First, find the inorder successor of the node to be deleted.
• After that, replace that node with the inorder successor until the target node is placed at the
leaf of tree.
• And at last, replace the node with NULL and free up the allocated space.
PROGRAM
#include <stdio.h> #include
<stdlib.h>
struct Node { struct
Node *lchild; int
data;
struct Node *rchild;
} *root = NULL;
void Inorder(struct Node *p) { if
(p) {
Inorder(p->lchild); printf("%d
", p->data);
Inorder(p->rchild);
}
}
struct Node *RInsert(struct Node *p, int key) {
struct Node *t = NULL;
if (p == NULL) { t = (struct Node
*)malloc(sizeof(struct Node)); t->data = key;
t->lchild = t->rchild = NULL; return
t;
} Page | 80 if (key < p->data) p->lchild = RInsert(p->lchild, key);
else if (key > p->data)
p->rchild = RInsert(p->rchild, key);
return p;
}
int Height(struct Node *p) {
int x, y; if (p ==
NULL) return 0; x =
Height(p->lchild); y =
Height(p->rchild);
return x > y ? x + 1 : y + 1;
}
struct Node *InPre(struct Node *p) {
while (p && p->rchild != NULL) p
= p->rchild;
return p;
}
struct Node *InSucc(struct Node *p) {
while (p && p->lchild != NULL) p
= p->lchild;
return p;
}
struct Node *Delete(struct Node *p, int key) {
struct Node *q; if (p == NULL) return NULL; if (p-
>lchild == NULL && p->rchild == NULL) { if (p ==
root)
root = NULL;
free(p); return
NULL;
}
if (key < p->data) p->lchild =
Delete(p->lchild, key);
else if (key > p->data)
p->rchild = Delete(p->rchild, key);
else {
if (Height(p->lchild) > Height(p->rchild)) {
q = InPre(p->lchild); p->data
= q->data;
p->lchild = Delete(p->lchild, q->data);
}
else { q = InSucc(p-
>rchild); p-
>data = q->data;
p->rchild = Delete(p->rchild, q->data);
}
}
Page | 81
return p;
}
int main() { struct Node
*temp; root =
RInsert(root, 50);
RInsert(root, 10);
RInsert(root, 40);
RInsert(root, 20); RInsert(root,
30);
printf("Before Deletion:\n");
Inorder(root); printf("\n");
Delete(root, 30);
printf("After Deletion:\n");
Inorder(root);
return 0; }
OUTPUT:
11. Graphs
Depth First Search
ALGORITHM Page | 83
Step 1. Create a stack with the total number of vertices in the
graph as the size.
Step 2. Choose any vertex as the traversal's beginning
point. Push a visit to that vertex and add it to
the stack.
Step 3. Push any non-visited adjacent vertices of a vertex at the top of the stack to the top of the stack.
Step 4. Repeat steps 3 and 4 until there are no more vertices to visit from the vertex at the top of the
stack.
Step 5. If there are no new vertices to visit, go back and pop one from the stack using backtracking.
Step 6. Continue using steps 3, 4, and 5 until the stack is empty.
Step 7. When the stack is entirely unoccupied, create the final spanning tree by deleting the graph's
unused edges.
PROGRAM
#include<stdio.h>
#include<stdlib.h> struct
node { int
vertexNumber;
struct node *pointerToNextVertex;
};
struct Graph { int
numberOfVertices;
int *visitedRecord;
struct node **adjacencyLists;
};
struct node *createNodeForList(int v) { struct node
*newNode = malloc(sizeof(struct node));
newNode->vertexNumber = v; newNode-
>pointerToNextVertex = NULL; return newNode;
}
void addEdgeToGraph(struct Graph *graph, int source, int destination) {
struct node *newNode = createNodeForList(destination); newNode-
>pointerToNextVertex = graph->adjacencyLists[source]; graph-
>adjacencyLists[source] = newNode; newNode =
createNodeForList(source); newNode->pointerToNextVertex = graph-
>adjacencyLists[destination]; graph->adjacencyLists[destination] =
newNode;
}
struct Graph *createGraph(int vertices) {
int i;
struct Graph *graph = malloc(sizeof(struct Graph)); graph->numberOfVertices
= vertices;
graph->adjacencyLists = malloc(vertices * sizeof(struct node *));
graph->visitedRecord = malloc(vertices * sizeof(int)); for
(i = 0; i < vertices; i++) { graph->adjacencyLists[i] =
NULL;
graph->visitedRecord[i] = 0;
}
return graph; Page | 84
}
void depthFirstSearch(struct Graph *graph, int vertexNumber) {
struct node *adjList = graph->adjacencyLists[vertexNumber];
struct node *temp = adjList; graph-
>visitedRecord[vertexNumber] = 1; printf("%d ",
vertexNumber); while (temp != NULL) { int
connectedVertex = temp->vertexNumber; if (graph-
>visitedRecord[connectedVertex] == 0)
depthFirstSearch(graph, connectedVertex);
temp = temp->pointerToNextVertex;
}
}
int main() { int numberOfVertices,
numberOfEdges, i;
int source, destination; int startingVertex; printf("Enter
Number of Vertices and Edges in the Graph: "); scanf("%d
%d", &numberOfVertices, &numberOfEdges); struct Graph
*graph = createGraph(numberOfVertices);
printf("Add %d Edges of the Graph(Vertex numbering should be from 0 to %d)\n", numberOfEdges,
numberOfVertices - 1);
for (i = 0; i < numberOfEdges; i++) { scanf("%d%d",
&source, &destination);
addEdgeToGraph(graph, source, destination);
}
printf("Enter Starting Vertex for DFS Traversal: ");
scanf("%d", &startingVertex); if (startingVertex <
numberOfVertices) {
printf("DFS Traversal: ");
depthFirstSearch(graph, startingVertex);
}
return 0;
}
OUTPUT:
PROGRAM
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct Graph_t
{ int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V; for (int i = 0;
i < V; i++)
{
for (int j = 0; j < V; j++)
{ g->adj[i][j] = false;
}
}
return g;
}
void Graph_destroy(Graph* g)
{
free(g);
}
void Graph_addEdge(Graph* g, int v, int w)
{ g->adj[v][w] = true;
}
void Graph_BFS(Graph* g, int s)
{
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++)
{
visited[i] = false;
}
int queue[MAX_VERTICES];
int front = 0, rear = 0; Page | 86 visited[s] = true; queue[rear++] = s;
while (front != rear)
{
s = queue[front++]; printf("%d ", s); for (int
adjacent = 0; adjacent < g->V; adjacent++)
{ if (g->adj[s][adjacent] && !visited[adjacent])
{ visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}
int main()
{
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3); Graph_addEdge(g,
3, 3);
printf("Following is Breadth First Traversal (starting from vertex 2) \n");
Graph_BFS(g, 2); Graph_destroy(g);
return 0;
}
OUTPUT:
KRUSKAL’S ALGORITHM
ALGORITHM
1. Sort all the edges from low weight to high
2. Take the edge with the lowest weight and add it to the spanning tree. If adding the edge
created a cycle, then reject this edge. 3. Keep adding edges until we reach all vertices.
PROGRAM
#include<stdio.h> #define
MAX 30
typedef struct edge
{
int u, v, w; Page | 87
} edge; typedef struct
edge_list
{
edge data[MAX];
int n; }
edge_list;
edge_list elist; int
Graph[MAX][MAX], n;
edge_list spanlist; void
kruskalAlgo();
int find(int belongs[], int vertexno); void
applyUnion(int belongs[], int c1, int c2); void
sort(); void print();
void kruskalAlgo()
{ int belongs[MAX], i, j, cno1, cno2; elist.n
= 0; for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
{
if (Graph[i][j] != 0)
{ elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}}
sort();
for (i = 0; i < n; i++) belongs[i]
= i;
spanlist.n = 0;
for (i = 0; i < elist.n; i++)
{ cno1 = find(belongs, elist.data[i].u); cno2
= find(belongs, elist.data[i].v); if
(cno1 != cno2)
{ spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
int find(int belongs[], int vertexno)
{ return (belongs[vertexno]);
}
Page | 88 void applyUnion(int belongs[], int c1, int c2)
{
int i;
for (i = 0; i < n; i++) if
(belongs[i] == c2)
belongs[i] = c1;
}
void sort()
{
int i, j;
edge temp;
for (i = 1; i < elist.n; i++) for (j = 0; j < elist.n - 1; j++) if
(elist.data[j].w > elist.data[j + 1].w)
{ temp = elist.data[j]; elist.data[j] =
elist.data[j + 1];
elist.data[j + 1] = temp;
}
}
void print()
{ int i, cost = 0; for (i = 0; i <
spanlist.n; i++)
{ printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w); cost =
cost + spanlist.data[i].w;
}
printf("\nSpanning tree cost: %d", cost);
}
int main()
{ int i, j, total_cost; n = 6;
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;
Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0; Page | 89
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;
kruskalAlgo(); print();
}
OUTPUT:
PRIM’S ALGORITHM
ALGORITHM
Step 1. Determine an arbitrary vertex as the starting vertex of the MST.
Step 2. Follow steps 3 to 5 till there are vertices that are not included in the MST (known as fringe
vertex).
Step 3. Find edges connecting any tree vertex with the fringe vertices. Step
4. Find the minimum among these edges.
Step 5. Add the chosen edge to the MST if it does not form any cycle. Step
6. Return the MST and exit
PROGRAM
#include <limits.h>
#include <stdbool.h>
Page | 90
#include <stdio.h> #define
V5
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index; for (int v = 0;
v < V; v++) if (mstSet[v] == false && key[v] <
min) min = key[v], min_index = v;
return min_index;
}
int printMST(int parent[], int graph[V][V]) {
printf("Edge \tWeight\n"); for (int i = 1; i < V; i++) printf("%d -
%d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
void primMST(int graph[V][V]) {
int parent[V]; int
key[V];
bool mstSet[V];
for (int i = 0; i < V; i++) key[i] = INT_MAX,
mstSet[i] = false; key[0] = 0; parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true; for (int v =
0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v]
= u, key[v] = graph[u][v];
}
printMST(parent, graph);
}
int main() {
int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0
} };
primMST(graph);
return 0;
}
OUTPUT: