DFS Lab File
DFS Lab File
Searching
LINEAR SEARCH
ALGORITHM Page | 1
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);
Step 6. setting position as -1 then entering the loop to compare every component of
array with the element
Step 7. if element is found set pos to i+1 and exit the loop
int pos=-1;
for(int i=0;i<size;i++)
{
if(Arr[i]==ele)
{
pos=i+1;
break;
}
}
Step 8. now if pos is -1 print element is not found
if(pos==-1)
printf("Element not Found!\n");
Step 9. otherwise print element with its position in the array
else
printf("%d found at position %d.",ele,pos);
Step 10. If ans to STEP 4 was N, exit the program
case 'N':
case 'n':
exit(0);
Step 11. if any other character instead of Y or N is entered show:
default:
cout<<"\nWrong Choice!\n";
Step 12. end
PROGRAM -> LSEARCH.CPP
//INCLUDING NECESSARY HEADER FILES
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h> Page | 2
int Arr[100];
//CREATION OF THE ARRAY
void createar(int size)
{
printf("Enter Elements in Array:");
for(int i=0;i<size;i++)
scanf("%d",&Arr[i]);
}
//LINEAR SEARCH FUNCTION
void lsearch(int ele,int size)
{
int pos=-1;
for(int i=0;i<size;i++)
{
if(Arr[i]==ele)
{
pos=i+1;
break;
}
}
if(pos==-1)
printf("Element not Found!\n");
else
printf("%d found at position %d.",ele,pos);
}
//MAIN FUNCTION
void main()
{
clrscr();
int size,ele;
printf("Enter Size of Array:");
scanf("%d",&size);
createar(size);
char Y='y';
while(Y)
{
cout<<"\nDo you want to search an element? (Y/N)";
cin>>Y;
switch(Y)
{
case 'Y':
case 'y':
printf("Enter Element to search:");
scanf("%d",&ele); Page | 3
lsearch(ele,size);
getch();
break;
case 'N':
case 'n':
exit(0);
default:
cout<<"\nWrong Choice!\n";
getch();
}
}
}
OUTPUTS
First Output
If Y
--Element is found
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 (high+low)/2
mid=(low+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. when the loop exits return -1
return -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
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]<<" "; Page | 8
}
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();
}
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) Page | 9
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];
//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 Page | 10
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)
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--;
} Page | 11
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
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++) Page | 12
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) {
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);
}
void qsort(int low,int high) {
if(low<high) {
int pi=part(low,high);
disp();
qsort(low,pi-1);
qsort(pi+1,high); Page | 13
}
}
void main() {
clrscr();
cout<<"Enter size of Array:";
cin>>size;
cout<<"Enter numbers in Array:";
for(int i=0;i<size;i++)
cin>>Arr[i];
cout<<"Array you entered:"<<endl;
disp();
cout<<"Array after each step:"<<endl;
qsort(0,size-1);
cout<<"Sorted Array:"<<endl;
disp();
getch();
}
OUTPUT
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 Page | 14
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++)
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++; Page | 15
}
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;
cout<<"Enter elements into the Array:";
for(int i=0;i<size;i++)
cin>>arr[i];
cout<<endl<<"Entered Array:"<<endl;
print();
mergesort(0,size-1);
cout<<endl<<"Sorted Array:"<<endl;
print();
getch();
}
OUTPUT
3. Singly Linked List
ALGORITHMS
a. Creation of the Linked List / Definition
struct LinkedList //Definition
Page | 16
{
int data; //Information
LinkedList *next; //pointer to next node
};
LinkedList *first; //first node of the Linked LIst
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;
Step 5. Otherwise traverse to the last node and add the new node to the end Page | 17
else
LinkedList *ptr=first;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=n;
Step 6. End
PROGRAM SLL.CPP
//INCLUDING ALL NECESSARY HEADER FILES
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
//CREATION OF SINGLY LINKED LIST
struct LinkedList {
int data;
LinkedList *next;
};
LinkedList *first; Page | 21
//DISPLAY LINKED LIST
void display() {
LinkedList *ptr=new LinkedList;
ptr=first;
if(first==NULL)
cout<<"Empty List.";
while(ptr!=NULL)
{
cout<<ptr->data;
if(ptr->next!=NULL)
cout<<" --> ";
ptr=ptr->next;
}
getch();
}
//INSERTION AT BEGINNING
void Insertb(int item) {
LinkedList *n=new LinkedList;
n -> data= item;
n->next=first;
first=n;
display();
}
//INSERTION AT END
void Inserte(int item) {
LinkedList *n=new LinkedList;
n -> data= item;
n->next=NULL;
if(first==NULL)
first=n;
else {
LinkedList *ptr=first;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=n;
}
display();
}
//INSERTION AT ANY POSITION
void Inserta(int item) {
clrscr();
cout<<"1. INSERT AFTER PARTICULAR ELEMENT.\n";
cout<<"2. INSERT AT PARTICULAR POSITION.\n";
cout<<"GIVE YOUR CHOICE!\n";
int ch2;
cin>>ch2; Page | 22
if(ch2==1) {
int ele;
cout<<"Enter the element:";
cin>>ele;
LinkedList *n= new LinkedList;
n->data=item;
LinkedList *ptr=first;
while(ptr->data!=ele && ptr!=NULL) {
ptr=ptr->next;
}
if(ptr==NULL)
cout<<"Element NOT found.\n";
else {
n->next=ptr->next;
ptr->next=n;
ptr=n;
}
}
if(ch2==2) {
int pos,var=1;
cout<<"Enter the position:";
cin>>pos;
LinkedList *n= new LinkedList;
LinkedList *prev=new LinkedList;
n->data=item;
n->next=NULL;
LinkedList *ptr=first;
if(first==NULL && pos==1)
first=n;
while(var!=pos && ptr!=NULL) {
prev=ptr;
ptr=ptr->next;
var++;
}
if(ptr==NULL && var==pos) {
prev->next=n;
n->next=NULL;
}
else if(ptr!=NULL) {
n->next=prev->next;
prev->next=n;
}
else
cout<<"Position NOT found!\n";
}
display();
}
//DELETION FROM BEGINNING Page | 23
void Delb() {
if(first==NULL)
cout<<"List is Empty!\n";
else {
cout<<"\nDeleted Element:\n"<<first->data;
first=first->next;
cout<<"\nNew Linked List:\n";
display();
}
}
//DELETION FROM END
void Dele() {
if(first==NULL)
cout<<"List is Empty!\n";
else {
LinkedList *ptr=first;
while(ptr->next->next!=NULL) {
ptr=ptr->next;
}
cout<<"\nDeleted Element:\n"<<ptr->next->data;
ptr->next=NULL;
cout<<"\nNew List:\n";
if(first->next==NULL)
first=NULL;
display();
}
}
//DELETION FROM ANY POSITION
void Dela() {
clrscr();
cout<<"1. DELETE PARTICULAR ELEMENT.\n";
cout<<"2. DELETE FROM PARTICULAR POSITION.\n";
cout<<"GIVE YOUR CHOICE!\n";
int ch2;
cin>>ch2;
if(ch2==1)
{
int ele;
cout<<"Enter the element:";
cin>>ele;
LinkedList *ptr=first;
LinkedList *prev=new LinkedList;
if(first->data==ele) {
cout<<"\nDeleted Element:\n"<<first->data;
first=first->next;
}
while(ptr->data!=ele && ptr!=NULL) {
prev=ptr; Page | 24
ptr=ptr->next;
}
if(ptr==NULL)
cout<<"Element NOT found.\n";
else {
cout<<"\nDeleted Element:\n"<<ptr->data;
prev->next=ptr->next;
cout<<"\nNew List:\n";
}
}
if(ch2==2) {
int pos,var=1;
cout<<"Enter the position:";
cin>>pos;
LinkedList *ptr=first;
LinkedList *prev=new LinkedList;
if(pos==1)
first=first->next;
while(var!=pos && ptr!=NULL) {
prev=ptr;
ptr=ptr->next;
var++;
}
if(ptr==NULL)
cout<<"Position NOT found.\n";
else {
cout<<"\nDeleted Element:\n"<<ptr->data;
prev->next=ptr->next;
cout<<"\nNew List:\n";
}
}
display();
}
//SEARCHING AN ELEMENT
void Srch() {
int ele,f=0,pos=1;
cout<<"Enter element you want to search:";
cin>>ele;
LinkedList *ptr=first;
while(ptr!=NULL) {
if(ptr->data==ele) {
f=1;
break;
}
else {
pos++;
ptr=ptr->next;
} Page | 25
}
if(f==1)
cout<<ele<<" found at "<<pos<<endl;
else
cout<<"NOT FOUND!";
getch();
}
void main() {
int item;
while(1) {
clrscr();
cout<<" MENU\n";
cout<<"1. DISPLAY (TRAVERSE)\n";
cout<<"2. INSERT BEGIN\n";
cout<<"3. INSERT END\n";
cout<<"4. INSERT AT ANY POSITION\n";
cout<<"5. DELETE FROM BEGINNING\n";
cout<<"6. DELETE FROM END\n";
cout<<"7. DELETE FROM ANY POSITION\n";
cout<<"8. SEARCH AN ELEMENT\n";
cout<<"9. EXIT\n";
cout<<"ENTER YOUR CHOICE:\n";
int ch;
cin>>ch;
switch(ch) {
case 1: display();
break;
case 2: cout<<"ENTER DATA TO INPUT:";
cin>>item;
Insertb(item);
break;
case 3: cout<<"ENTER DATA TO INPUT:";
cin>>item;
Inserte(item);
break;
case 4: cout<<"ENTER DATA TO INPUT:";
cin>>item;
Inserta(item);
break;
case 5: Delb();
break;
case 6: Dele();
break;
case 7: Dela();
break;
case 9: exit(0);
case 8: Srch();
break; Page | 26
default: cout<<"INVALID CHOICE!";
getch();
}
}
}
OUTPUTS
Main function start
Page | 27
Page | 28
8 Searching
-- When element is found
9 Exit
4. Doubly Linked List
ALGORITHMS
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;
Step 6. end
d. Insertion at End
Step 1. Start
Step 2. Create a temporary node
DLL *n=new DLL; Page | 31
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. Check if first is NULL and set the temporary node as first if the condition is
true.
if(first==NULL)
first=n;
Step 5. Otherwise traverse to the last node and add the new node to the end
else
DLL *ptr=first;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=n;
n->prev=ptr;
Step 6. End
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 | 36
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 | 37
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 | 38
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 | 39
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 | 40
}
else {
while(ptr->next!=NULL && ptr->data!=ele) {
ptr=ptr->next;
}
if(ptr->next==NULL && ptr->data!=ele)
cout<<"Element NOT found\n";
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 | 41
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 | 43
-- If element is found
Page | 44
10. Exit
Exiting show this screen
5. Circular Singly Linked List
ALGORITHMS
//Definition of Linked List node
Page | 45
struct node {
int data;
struct node *next;
};
struct node *head;
//Display/Traversal
Step 1. Set ptr = head
Step 2. if ptr = null
write "empty list"
goto step 7
end of if
Step 3. Repeat step 4 and 5 until ptr → next != head
Step 4. print ptr → data
Step 5. ptr = ptr → next
[end of loop]
Step 6. print ptr→ data
Step 7. exit
//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
Step 4. set new_node -> data = val
Step 5. set new_node -> next = head
Step 6. set temp = head
Step 7. repeat step 8 while temp -> next != head
Step 8. set temp = temp -> next
[end of loop] Page | 46
Step 9. set temp -> next = new_node
Step 10. exit
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 {
printf("\nEnter the element value:"); Page | 48
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 {
ptr = head; Page | 49
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;
i++; Page | 50
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 | 51
6. Circular Doubly Linked List
ALGORITHMS
//Definition of Linked List node
Page | 52
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
Step 1. if ptr = null
write overflow
go to step 12
[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 new_node -> next = head
Step 6. set temp = head
Step 7. repeat step 8 while temp -> next != head
Step 8. set temp = temp -> next
[end of loop]
Step 9. set temp -> next = new_node
Step 10. set new_node -> prev = temp
Step 11. set head -> prev = new_node
Step 12. exit
//Deletion from Beginning
Step 1. if head = null
write underflow
go to step 8
[end of if]
Step 2. set temp = head Page | 53
Step 3. repeat step 4 while temp -> next!= head
Step 4. set temp = temp -> next
[end of loop]
Step 5. set temp -> next = head -> next
Step 6. set head -> next -> prev = temp
Step 7. free head
Step 8. set head = temp -> next
Step 9. 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;
ptr -> prev = head; Page | 54
}
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)
printf("\n UNDERFLOW"); Page | 55
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 | 56
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;
while(choice != 9) { Page | 57
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
Stack is a LIFO structure, i.e., Last In First Out Structure, the element inserted latest will be deleted Page | 58
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;
S[top]=ele; Page | 59
}
}
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;
case 2: pop(); Page | 60
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 | 61
//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 | 62
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 | 63
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 | 64
//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 | 65
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 | 66
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 | 67
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 | 69
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 | 70
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 | 71
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]);
rear=-1; Page | 72
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 | 73
9. File Handling
getc() and putc():
PROGRAM
#include<stdio.h>
Page | 74
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 | 75
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 | 76
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 | 77
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 | 78
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);
}
}
return p;
Page | 79
}
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:
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;
} Page | 82
return graph;
}
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:
Page | 83
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) Page | 84
{
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++)
{
visited[i] = false;
}
int queue[MAX_VERTICES];
int front = 0, rear = 0;
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
Page | 85
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;
} 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; Page | 86
applyUnion(belongs, cno1, cno2);
}
}
}
int find(int belongs[], int vertexno)
{
return (belongs[vertexno]);
}
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; Page | 87
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;
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.
Page | 88
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>
#include <stdio.h>
#define V 5
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:
Page | 89