Lab mannual for DSA for NEP(1)
Lab mannual for DSA for NEP(1)
Experiment No. 1
Aim: Write a c program to implement insertion, deletion and traversing of elements
in an array.
THEORY:
What is an Array?
An array is a type of linear data structure that is defined as a collection of elements
with same or different data types. They exist in both single dimension and multiple
dimensions. These data structures come into picture when there is a necessity to
store multiple elements of similar nature together at one place.
The difference between an array index and a memory address is that the array
index acts like a key value to label the elements in the array. However, a memory
address is the starting address of free memory available.
Following are the important terms to understand the concept of Array.
● Element − Each item stored in an array is called an element.
● Index − Each location of an element in an array has a numerical index,
which is used to identify the element.
Array - Insertion Operation
In the insertion operation, we are adding one or more elements to the array. Based
on the requirement, a new element can be added at the beginning, end, or any given
index of array. This is done using input statements of the programming languages.
Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach the
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[10],i,n,ch,pos,ele;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe array is: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n1.Insert\n2.Delete\n3.Traverse\n4.Sorting\n5.Exit\n");
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the position where you want to insert the element: ");
scanf("%d",&pos);
printf("Enter the element you want to insert: ");
scanf("%d",&ele);
for(i=n-1;i>=pos-1;i--)
{
a[i+1]=a[i];
}
a[pos-1]=ele;
n++;
printf("\nThe array is: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
break;
case 2:
printf("Enter the position where you want to delete the element: ");
scanf("%d",&pos);
for(i=pos-1;i<n-1;i++)
{
a[i]=a[i+1];
}
n--;
printf("\nThe array is: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
break;
case 3:
printf("\nThe array is: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
break;
case 4:
for(i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nThe array is: ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
break;
case 5:
exit(0);
default:
printf("Invalid choice");
}
return 0;
}
OUTPUT:
Enter the size of the array: 10
Enter the elements of the array: 1
2
3
4
5
6
7
8
9
10
The array is: 1 2 3 4 5 6 7 8 9 10
1.Insert
2.Delete
3.Traverse
4.Sorting
5.Exit
Enter your choice: 1
Enter the position where you want to insert the element: 5
Enter the element you want to insert: 44
Experiment No.2
Aim: Write a program that implements the following sorting i)Bubble sort
ii)Selection sort iii)Quick sort.
Theory:
i) Bubble sort
The bubble sort is an example of exchange sort. In this method, repetitive
comparison is performed among elements and essential swapping of elements is
done. Bubble sort is commonly used in sorting algorithms. It is easy to
understand but time consuming i.e. takes more number of comparisons to sort a
list. In this type, two successive elements are compared and swapping is done.
Thus, step-by-step entire array elements are checked. It is different from the
selection sort. Instead of searching the minimum element and then applying
swapping, two records are swapped instantly upon noticing that they are not in
order.
Algorithm: Bubble_Sort ( A [ ] , N )
Step 1: Start
Step 2: Take an array of n elements
Step 3: for i=0,n-2
Step 4: for j=i+1,…….n-1
Step 5: if arr[j]>arr[j+1] then Interchange arr[j] and arr[j+1] End of if
Step 6: Print the sorted array arr
Step 7:Stop
Source Code: Program to Sort N Numbers in Ascending Order using Bubble Sort
#include <stdio.h>
#include<conio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num
\n"); scanf("%d", &num);
printf("Enter the elements one by one
\n"); for (i = 0; i<num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is
\n"); for (i = 0; i<num; i+
+)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins
*/ for (i = 0; i<num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...
\n"); for (i = 0; i<num; i++)
{
printf("%d\n", array[i]);
}
}
Output:
Enter the value of
num 6
Enter the elements one by
one 23 45 67 89 12 34
Input array is
23 45 67 89 12 34
Sorted array is...
12 23 34 45 67
89
Quick sort:
It is a divide and conquer algorithm. Quick sort first divides a large array into two
smaller sub-arrays: the low elements and the high elements. Quick sort can then
recursively sort the sub-arrays.
ALGORITHM:
Step 1: Pick an element, called a pivot, from the array.
Step 2: Partitioning: reorder the array so that all elements with values less than the
pivot come before the pivot, while all elements with values greater than the pivot
come after it (equal values can go either way). After this partitioning, the pivot is
in its final position. This is called the partition operation.
Step 3: Recursively apply the above steps to the sub-array of elements with
smaller values and separately to the sub-array of elements with greater values.
Source Code: Implement Quick Sort
#include <stdio.h>
int partition(int a[], int beg, int end);
void quickSort(int a[], int beg, int end);
void main()
{int i;
int arr[10];
printf("\n Enter the Number of
Elements: "); scanf("%d",&n);
printf("\n Enter %d Elements: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
quickSort(arr, 0, n);
printf("\n The sorted array is: \n");
for(i=0;i<10;i++)
printf(" %d\t", arr[i]);
}
int partition(int a[], int beg, int end)
{
int left, right, temp, loc, flag;
loc = left = beg;
right = end;
flag = 0;
while(flag != 1)
{
while((a[loc] <= a[right]) && (loc!
=right)) right--;
if(loc==right)
flag =1;
else if(a[loc]>a[right])
{
temp = a[loc];
a[loc] = a[right];
a[right] = temp;
loc = right;
}
if(flag!=1)
{
while((a[loc] >= a[left]) && (loc!
=left)) left++;
if(loc==left)
flag =1;
else if(a[loc] <a[left])
{
temp = a[loc];
a[loc] = a[left];
a[left] = temp;
loc = left;
}
}
}
return loc;
}
void quickSort(int a[], int beg, int end)
{int loc;
if(beg<end)
{
loc = partition(a, beg, end);
quickSort(a, beg, loc-1);
quickSort(a, loc+1, end);
}
}
Output:
Enter the number of
Elements: 10
Enter 10 Elements:
90,23,101,45,65,23,67,89,34,23
The sorted array
is: 23
23
23
34
45
65
67
89
90
101
Theory:
(i)Insertion Sort: It iterates, consuming one input element each repetition, and
growing a sorted output list. Each iteration, insertion sort removes one element
from the input data, finds the location it belongs within the sorted list, and inserts it
there. It repeats until no input elements remain.
Algorithm:
Step 1: start
Step 2: for i 1 to length(A)
Step 3: j i
Step 4: while j > 0 and A[j-1] > A[j]
Step 5: swap A[j] and A[j-1]
Step 6: j j - 1 Step 7: end while Step 8: end for Step 9: stop
Source Code: Implementation of Insertion Sort:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50], size, i, j, k, element, index; printf("Enter Array Size: "); scanf("%d", &size);
printf("Enter %d Array Elements: ", size); for(i=0; i<size; i++)
scanf("%d", &arr[i]); for(i=1; i<size; i++)
{
element = arr[i]; if(element<arr[i-1])
{
for(j=0; j<=i; j++)
{
if(element<arr[j])
{
index = j; for(k=i; k>j; k--)
arr[k] = arr[k-1]; break;
}
}
}
else continue;
arr[index] = element;
}
printf("\nSorted Array:\n"); for(i=0; i<size; i++) printf("%d ", arr[i]); getch();
return 0;
}
Output:
Enter array size:
5
Enter 5 array elements:
28 16 5 11 0
Sorted Array:
0 5 11 16 28
ii) Merge sort: Merge sort is an O(n log n) comparison-based sorting algorithm. It
is stable, meaning that it preserves the input order of equal elements in the
sorted output. It is an example of the divide and conquer algorithmic paradigm.
Merge sort is so inherently sequential that it's practical to run it using slow tape
drives as input and output devices. It requires very little memory, and the memory
required does not change with the number of data elements. If you have four
tape drives, it works as follows:
1. Divide the data to be sorted in half and put half on each of two tapes.
2. Merge individual pairs of records from the two tapes; write two-record
chunks alternately to each of the two output tapes.
3. Merge the two-record chunks from the two output tapes into four-record
chunks; write these alternately to the original two input tapes.
4. Merge the four-record chunks into eight-record chunks; write these
alternately to the original two output tapes.
5. Repeat until you have one chunk containing all the data, sorted --- that is,
for log n
passes, where n is the number of records.
Conceptually, merge sort works as follows:
1. Divide the unsorted list into two sublists of about half the size.
2. Divide each of the two sublists recursively until we have list sizes of length
1, in which case the list itself is returned.
3. Merge the two sublists back into one sorted list.
Source Code: Implementation of Merge Sort:
#include<stdio.h>
int temp;
void heapify(int arr[], int size, int i)
{
int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left < size && arr[left] >arr[largest]) largest = left;
if (right < size && arr[right] > arr[largest]) largest = right;
if (largest != i)
{
temp = arr[i]; arr[i]= arr[largest]; arr[largest] = temp;
heapify(arr, size, largest);
}
}
void heapSort(int arr[], int size)
{
int i;
for (i = size / 2 - 1; i >= 0; i--) heapify(arr, size, i);
for (i=size-1; i>=0; i--)
{
temp = arr[0]; arr[0]= arr[i]; arr[i] = temp; heapify(arr, i, 0);
}
}
void main()
{
int arr[] = {1, 10, 2, 3, 4, 1, 2, 100,23, 2};
int i;
int size = sizeof(arr)/sizeof(arr[0]); heapSort(arr, size);
printf("printing sorted elements\n"); for (i=0; i<size; ++i) printf("%d\n",arr[i]);
}
Output:
printing sorted elements 1
1
2
2
2
3
4
10
23
100
iii) RADIX SORT
Radix sort is one of the sorting algorithms used to sort a list of integer numbers in
order. In radix sort algorithm, a list of integer numbers will be sorted based on the
digits of individual numbers. Sorting is performed from least significant digit to the
most significant digit. Radix sort algorithm requires the number of passes which
are equal to the number of digits present in the largest number among the list of
numbers. For example, if the largest number is a 3 digit number then that list is
sorted with 3 passes.
Step by Step Process
The Radix sort algorithm is performed using the following steps...
Step 1 - Define 10 queues each representing a bucket for each digit from 0 to 9.
Step 2 - Consider the least significant digit of each number in the list which is to be
sorted. Step 3 - Insert each number into their respective queue based on the least
significant digit. Step 4 - Group all the numbers from queue 0 to queue 9 in the
order they have inserted into their respective queues.
Step 5 - Repeat from step 3 based on the next least significant digit.
Step 6 - Repeat from step 2 until all the numbers are grouped based on the most
significant digit.
Algorithm for RadixSort (ARR, N)
Step 1: Find the largest number in ARR as LARGE
Step 2: [INITIALIZE] SET NOP = Number of digits in LARGE Step 3: SET PASS =
Step 4: Repeat Step 5 while PASS <= NOP-1 Step 5:SET I = and INITIALIZE buckets
Step 6:Repeat Steps 7 to 9 while I<N-1
Step 7:SET DIGIT = digit at PASSth place in A[I] Step 8:Add A[I] to the bucket
numbered DIGIT
Step 9:INCEREMENT bucket count for bucket numbered DIGIT [END OF LOOP]
Step 1 :Collect the numbers in the bucket [END OF LOOP]
Step 11: END
Source Code: Implementation of Radix sort
#include <stdio.h>
int largest(int a[]);
void radix_sort(int a[]);
void main()
{
int i;
int a[10]={90,23,101,45,65,23,67,89,34,23};
radix_sort(a);
printf("\n The sorted array is: \n");
for(i=0;i<10;i++) printf(" %d\t", a[i]);
}
int largest(int a[])
{
int larger=a[0], i;
for(i=1;i<10;i++)
{
if(a[i]>larger) larger = a[i];
}
return larger;
}
void radix_sort(int a[])
int bucket[10][10], bucket_count[10];
int i, j, k, remainder, NOP=0, divisor=1, larger, pass;
larger = largest(a);
while(larger>0)
{ NOP++;
larger/=10;
}
for(pass=0;pass<NOP;pass++) // Initialize the buckets
{
for(i=0;i<10;i++)
bucket_count[i]=0;
for(i=0;i<10;i++)
{
// sort the numbers according to the digit at passth place
remainder = (a[i]/divisor)%10;
bucket[remainder][bucket_count[remainder]] = a[i];
bucket_count[remainder] += 1;
.}
// collect the numbers after PASS
pass
i=0;
for(k=0;k<10;k++)
{
for(j=0;j<bucket_count[k];j++)
{
a[i] = bucket[k][j];
i++;
}
.}
divisor *= 10;
}
}
Output:
The sorted array is:
23
23
23
34
45
65
67
89
90
101
Conclusion: Thus we have successfully executed a program that implements the
following algorithms i) Insertion sort ii) Merge sort iii) Radix sort.
Experiment No. 3
Aim: Write a program that implements Circular Queue using arrays. Write a
program that uses both recursive and non recursive functions to perform the
following searching operations for a Key value in a given list of integers: a)Linear
search b)Binary search.
Theory:
Circular Queue
This situation also says that Queue is Full and we cannot insert the new element
because 'rear' is still at last position. In the above situation, even though we have
empty positions in the queue we can not make use of them to insert the new
element. This is the major problem in a normal queue data structure. To overcome
this problem we use a circular queue data structure. Circular Queue A Circular
Queue can be defined as follows.
A circular queue is a linear data structure in which the operations are performed
based on FIFO (First In First Out) principle and the last position is connected back
to the first position to make a circle.
Example
Operations on Single Linked List
The following operations are performed on a Single Linked List
1. Creation
2. Insertion
3. Deletion
4. Display
Before we implement actual operations, first we need to set up an empty list. First,
perform the following steps before implementing actual operations.
1.Creation
Step 1 - Define a Node structure with two members data and next
Step 2 - Define a Node pointer 'head' and set it to NULL.
2.Insertion
In a single linked list, the insertion operation can be performed in three
ways. They are as follows...
2.1Inserting At Beginning of the list
2.2Inserting At End of the list
2.3Inserting At Specific location in the list
3. Deletion
In a single linked list, the deletion operation can be performed in three
ways. They are as follows...
3.1 Deleting from Beginning of the list
3.2 Deleting from End of the list
3.3 Deleting a Specific Node
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
void insertAtBeginning(int);
void insertAtEnd(int);
void insertBetween(int,int,int);
void display();
void removeBeginning();
void removeEnd();
void removeSpecific(int);
struct Node
{
int data;
struct Node *next;
}
*head = NULL;
void main()
{
int choice,value,choice1,loc1,loc2;
clrscr();
while(1)
{
mainMenu:
printf("\n\n****** MENU ******\n1. Insert\n2. Display\n3. Delete\n4.
Exit\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be insert: ");
scanf("%d",&value);
while(1)
{
printf("Where you want to insert: \n1. At Beginning\n2. At
End\n3.Between\nEnter your choice: ");
scanf("%d",&choice1);
switch(choice1)
{
case 1:insertAtBeginning(value);
break;
case 2:insertAtEnd(value);
break;
case 3:printf("Enter the two values where you wanto insert: ");
scanf("%d%d",&loc1,&loc2);
insertBetween(value,loc1,loc2);
break;
default: printf("\nWrong Input!! Try again!!!\n\n");
goto mainMenu;
}
goto subMenuEnd;
}
subMenuEnd:
break;
case 2:display(); break;
case 3:printf("Do you want to Delete: \n1. From Beginning\n2. From End\n3.
Spesific\nEnter your choice: ");
scanf("%d",&choice1);
switch(choice1)
{
case 1: removeBeginning();
break;
case 2: removeEnd();
break;
case 3:printf("Enter the value which you wanto delete: ");
scanf("&d",&loc2);
removeSpecific(loc2);
break;
default: printf("\nWrong Input!! Try again!!!\n\n");
goto mainMenu;
}
break;
case 4:exit(0);
default: printf("\nWrong input!!! Try again!!\n\n");
}
}
}
void insertAtBeginning(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(head == NULL)
{
newNode->next = NULL; head = newNode;
}
else
{
newNode->next = head; head = newNode;
}
printf("\nOne node inserted!!!\n");
}
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else
{
struct Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
printf("\nOne node inserted!!!\n");
}
void insertBetween(int value, int loc1, int loc2)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(head == NULL)
{
newNode->next = NULL;
head = newNode;
}
else
{
struct Node *temp = head;
while(temp->data != loc1 && temp->data != loc2)
temp = temp->next;
newNode->next = temp->next; temp->next = newNode;
}
printf("\nOne node inserted!!!\n");
}
void removeBeginning()
{
if(head == NULL)
printf("\n\nList is Empty!!!");
else
{
struct Node *temp = head; if(head->next == NULL)
{
head = NULL;
free(temp);
}
else
{
head = NULL; free(temp);
head = temp->next;
free(temp);
printf("\nOne node deleted!!!\n\n");
}
}
}
void removeEnd()
{
if(head == NULL)
{
printf("\nList is Empty!!!\n");
}
else
{
struct Node *temp1 = head,*temp2;
if(head->next == NULL)
head = NULL;
else
{
while(temp1->next != NULL)
{
temp2 = temp1;
temp1 = temp1->next;
}
temp2->next = NULL;
}
free(temp1);
printf("\nOne node deleted!!!\n\n");
}
}
void removeSpecific(int delValue)
{
struct Node *temp1 = head, *temp2;
while(temp1->data != delValue)
{
if(temp1 -> next == NULL)
{
printf("\nGiven node not found in the list!!!");
goto functionEnd;
}
temp2 = temp1;
temp1 = temp1 -> next;
}
temp2 -> next = temp1 -> next;
free(temp1);
printf("\nOne node deleted!!!\n\n");
functionEnd:
}
void display()
{
if(head == NULL)
{
printf("\nList is Empty\n");
}
else
{
struct Node *temp = head;
printf("\n\nList elements are - \n");
while(temp->next != NULL)
{
printf("%d",temp->data);
temp = temp->next;
}
printf("%d",temp->data);
}
}
Output:
Example
Operations on Double Linked List
In a double linked list, we perform the following operations...
1. Creation
2. Insertion
3. Deletion
4. Display
1.Creation
Step 1 - Define a Node structure with two members data and next
Step 2 - Define a Node pointer 'head' and set it to NULL
2. Insertion
In a double linked list, the insertion operation can be performed in three ways as
follows...
2.1. Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the double
linked list.
Step 1 - Create a newNode with given value and newNode ! previous as NULL
.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to newNode ! next and newNode to head.
Step 4 - If it is not Empty then, assign head to newNode ! next and newNode to
head.
2.2. Inserting At End of the list
We can use the following steps to insert a new node at end of the double
linked list Step 1 - Create a newNode with given value and newNode !
next as NULL.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty, then assign NULL to newNode !
previous and newNode to head.
Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the last node in
the list (until temp ! next is equal to NULL).
Step 6 - Assign newNode to temp ! next and temp to newNode ! previous.
2.3. Inserting At Specific location in the list(after a node)
We can use the following steps to insert a new node after a node in the double
linked list.
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to both newNode ! previous &
newNode ! next and set newNode to head.
Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and
initialize temp1 with head.
Step 5 - Keep moving the temp1 to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 ! data is equal to location,
here location is the node value after which we want to insert the newNode).
Step 6 - Every time check whether temp1 is reached to the last node. If it is
reached to the last node then display 'Given node is not found in the list!!!
Insertion not possible!!!' and terminate the function. Otherwise move the temp1
to next node.
Step7- Assign temp1! next to temp2, newNode to temp1 ! next,
temp1 to newNode ! previous, temp2 to newNode ! nextand
newNode to temp2 ! previous.
3.Deletion
In a double linked list, the deletion operation can be performed in three ways as
follows...
3.1. Deleting from Beginning of the list
3.2. Deleting from End of the list
3.3. Deleting a Specific Node
3.1 Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the double
linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible'
and terminate the function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with
head.
Step 4 - Check whether list is having only one node (temp ! previous is equal to
temp ! next)
Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list
conditions)
Step 6 - If it is FALSE, then assign temp ! next to head, NULL to head ! previous
and delete temp.
3.2 Deleting from End of the list
We can use the following steps to delete a node from end of the double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Check whether list has only one Node (temp ! previous and temp ! next
both are NULL)
Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate
from the function. (Setting Empty list condition)
Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node in
the list. (until temp ! next is equal to NULL)
Step 7 - Assign NULL to temp ! previous ! next and delete temp.
3.3 Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the double linked
list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and
terminate the function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4 - Keep moving the temp until it reaches to the exact node to be deleted or
to the last node.
Step 5 - If it is reached to the last node, then display 'Given node not found in the
list!
Deletion not possible!!!' and terminate the function
Step 6 - If it is reached to the exact node which we want to delete, then check
whether list is having only one node or not
Step 7 - If list has only one node and that is the node which is to be
deleted then set head to NULL and delete temp (free(temp)).
Step 8 - If list contains multiple nodes, then check whether temp is the
first node in the list (temp == head).
Step 9 - If temp is the first node, then move the head to the next node (head = head
! next), set head of previous to NULL (head ! previous = NULL) and delete temp.
Step 10 - If temp is not the first node, then check whether it is the last node in the
list
(temp ! next==NULL).
Step 11 - If temp is the last node then set temp of previous of next to NULL
(temp ! previous ! next = NULL) and delete temp(free(temp)).
Step 12 - If temp is not the first node and not the last node, then set temp of
previous of next to temp of next (temp ! previous ! next = temp! next),temp of
next of previous to temp of previous (temp ! next ! previous = temp ! previous)
and delete temp(free(temp)).
4.Displaying
We can use the following steps to display the elements of a double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4 - Display 'NULL <--- '.
Step 5 - Keep displaying temp ! data with an arrow (<===>) until temp reaches to
the last node
Step 6 - Finally, display temp ! data with arrow pointing to NULL
(temp ! data ---> NULL).
Experiment No. 6
Theory:
That means circular linked list is similar to the single linked list except that the
last node points to the first node in the list
Example:
Operations
In a circular linked list, we perform the following operations...
1. Creation
2.
Insertion
3. Deletion
4. Display
1.Creation
Step 1 - Define a Node structure with two members
Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize
with 'head'.
Step 5 - Keep moving the 'temp' to its next node until it reaches to the
last node (until 'temp ! next == head').
Step 6 - Set 'newNode ! next =head', 'head = newNode' and 'temp ! next
= head'.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and
'temp2' and initialize both 'temp1' and 'temp2' with head.
Step 4 - Check whether list is having only one node (temp1 ! next ==
head)
Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting
Empty list conditions)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And
terminate from the function. (Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its
next node.
Repeat the same until temp1 reaches to the last node in the list.
(until temp1 ! next == head)
Step 7 - Set temp2 ! next = head and delete temp1.
3.3 Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the circular linked
list...
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize
with head.
Step 4 - Keep displaying temp ! data with an arrow (--->) until temp
reaches to the last node
struct Node
{
int data;
struct Node *next;
}*head = NULL;
void main()
{
int choice1, choice2,
value, location; clrscr();
while(1)
{
cout<<"\n*********** MENU *************\n";
cout<<"1. Insert\n2. Delete\n3. Display\n4. Exit\nEnter your
choice: "; cin>>choice1;
switch(choice1)
{
case 1: cout<<"Enter the value to be
inserted: "; cin>>value;
while(1)
{
cout<<"\nSelect from the following Inserting options\n";
cout<<"1. At Beginning\n2. At End\n3. After a Node\n4.
Cancel\nEnter your choice: ";
cin>>choice2
;
switch(choice
2)
{
case
1:insertAtBegi
nning(value);
break;
case 2:insertAtEnd(value);
break;
case 3:cout<<"Enter the location after which you
want to insert:"; cin>>location;
insertAfter(value,loc
ation); break;
}
}
EndSw
itch: break;
case 3:
display();
b
reak;
case
4:
exit(0
);
default: cout<<"\nPlease select correct option!!!";
}
}
}
void insertAtBeginning(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode -> data = value;
if(head == NULL)
{
head =
newNode;
newNode ->
next = head;
}
else
{
struct Node
*temp = head;
while(temp ->
next != head)
temp = temp ->
next; newNode ->
next = head;
head = newNode;
temp -> next = head;
}
cout<<"\nInsertion success!!!";
}
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct
Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
head =
newNode;
newNode ->
next = head;
}
else
{
struct Node
*temp = head;
while(temp ->
next != head)
temp = temp
-> next; temp
-> next =
newNode;
newNode ->
next = head;
}
cout<<"\nInsertion success!!!";
}
void insertAfter(int value, int location)
{
}
cout<<"\nDeletion success!!!";
}
}
void deleteEnd()
{
if(head == NULL)
cout<<"List is Empty!!! Deletion not
possible!!!"; else
{
struct Node *temp1 =
head, temp2; if(temp1
-> next == head)
{
hea
d=
NULL;
free
(temp1);
}
else
{
while(temp1 -> next !
= head){ temp2 =
temp1;
temp1 = temp1 -> next;
}
temp2 -> next =
head; free(temp1);
}
cout<<"\nDeletion success!!!";
}
}
void deleteSpecific(int delValue)
{
if(head == NULL)
cout<<"List is Empty!!! Deletion not
possible!!!"; else
{
struct Node *temp1 =
head, temp2; while(temp1
-> data != delValue)
{
if(temp1 -> next == head)
{
cout<<"\nGiven node is
not found in the list!!!";
goto FuctionEnd;
}
else
{
temp2 = temp1;
}
}
if(temp1 -> next == head)
{
head =
NULL;
free(temp1);
}
else
{
if(temp1 == head)
{
temp2 = head;
while(temp2 -> next !=
head) temp2 = temp->
next;
head =
head ->
next;
temp2 ->
next =
head;
free(temp
1);
}
else
{
if(temp1 -> next == head)
{
if(temp1 -> next == head)
{
temp2 -> next = head;
}
else
{
temp2 -> next = temp1 -> next;
}
free(temp1);
}
}
cout<<"\nDeletion success!!!";
}
FuctionEnd:
}
void display()
{
if(head == NULL)
cout<<"\nList is
Empty!!!"; else
{
struct Node *temp =
head; cout<<"\nList
elements are: \n";
O
u
t
p
u
t:
Conclusion: Thus, we have successfully execute the program that uses functions
to perform the following operations on circular linked List (i)Creation (ii) Insertion
(iii) Deletion (iv) Traversal.
Date:_________
Experiment No. 7
Aim: Write a program that implement stack (its operations) using
(i)Arrays(ii)Linked list(Pointers).
Theory:
Stack
Stack is a linear data structure in which the insertion and deletion
operations are performed at only one end. In a stack, adding and removing of
elements are performed at a single position which is known as "top".
That means, a new element is added at top of the stack and an element
is removed from the top of the stack. In stack, the insertion and deletion
operations are performed based on LIFO(Last In First Out) principle.
Program:
Source Code: To implement Stack Using Arrays
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;
void main()
{
int value, choice; clrscr();
while(1)
{
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void push(int value)
{
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else
{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
}
void pop()
{
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted :%d"stack[top]);
top--;
}
}
void display()
{
if(top == -1)
printf("\nStack is Empty!!!");
else
{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d", stack[i]);
}
}
Output:
Conclusion: Thus, we have successfully execute the program that implement stack
(its operations) using (i)Arrays(ii)Linked list (Pointers).
Date:__________
Experiment No. 8
Aim: Write a program that implement Queue (its operations) using (i)Arrays
(ii)Linked list(Pointers).
Theory:
Queue Using Arrays
A queue data structure can be implemented using one dimensional array.
The queue implemented using array stores only fixed number of data values.
The implementation of queue data structure using array is very simple. Just
define a one-dimensional array of specific size and insert or delete the values into
that array by using FIFO (First In First Out) principle with the help of variables
'front' and 'rear'. Initially both 'front' and 'rear' are set to -1.
Whenever, we want to insert a new value into the queue, increment 'rear'
value by one and then insert at that position. Whenever we want to delete a value
from the queue, then delete the element which is at 'front' position and increment
'front' value by one.
Queue Operations using Array
We can Perform the following operations
on Queue 1.enQueue()
2.deQu
eue()
3.Displ
ay()
Before we implement actual operations, first follow the below steps to create an
empty queue.
Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2 - Declare all the user defined functions which are used in queue
implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int queue[SIZE]).
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int
front = -1, rear = -1).
Step 5 - Then implement main method by displaying menu of operations list and
make suitable function calls to perform operation selected by the user on queue
1.enQueue(value) - Inserting value into the queue
In a queue data structure, enQueue() is a function used to insert a new element into
the queue. In a queue, the new element is always inserted at rear position. The
enQueue() function takes one integer value as a parameter and inserts that value
into the queue. We can use the following steps to insert an element into the queue...
Step 1 - Check whether queue is FULL. (rear == SIZE-1)
Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and set
queue[rear] = value.
2. deQueue() - Deleting a value from the Queue
In a queue data structure, deQueue() is a function used to delete an element from
the queue. In a queue, the element is always deleted from front position. The
deQueue() function does not take any value as parameter. We can use the
following steps to delete an element from the queue...
In above example, the last inserted node is 50 and it is pointed by 'rear' and the first
inserted node is 10 and it is pointed by 'front'. The order of elements inserted is 10,
15, 22 and 50.
Queue Operations using Array
We can Perform the following operations on Queue 1.enQueue()
2.deQueue() 3.Display()
To implement queue using linked list, we need to set the following things before
implementing actual operations.
Step 1 - Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2 - Define a 'Node' structure with two members data and next.
Step 3 - Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4 - Implement the main method by displaying Menu of list of operations and
make suitable function calls in the main method to perform user selected
operation.
1.enQueue(value) - Inserting an element into the Queue
We can use the following steps to insert a new node into the queue...
Step 1 - Create a newNode with given value and set 'newNode ! next' to NULL.
Step 2 - Check whether queue is Empty (rear == NULL)
Step 3 - If it is Empty then, set front = newNode and rear = newNode.
Step 4 - If it is Not Empty then, set rear ! next = newNode and rear = newNode.
Experiment No. 9
Theory:
Dictionary
The most common objective of computer programs is to store and retrieve data.
Much of this book is about efficient ways to organize collections of data records
so that they can be stored and retrieved quickly. In this section we describe a
simple interface for such a collection, called a dictionary. The dictionary ADT
provides operations for storing records, finding records, and removing records from
the collection. This ADT gives us a standard basis for comparing various data
structures. Loosly speaking, we can say that any data structure that supports
insert, search, and deletion is a "dictionary".
Dictionaries depend on the concepts of a search key and comparable objects. To
implement the dictionary's search function, we will require that keys be totally
ordered. Ordering fields that are naturally multi-dimensional, such as a point in two
or three dimensions, present special opportunities if we wish to take advantage of
their multidimensional nature. This problem is addressed by spatial data
structures.
Output:
MENU FOR DICTIONARY OPERATIONS:
1. Create
2. Search for a value 3.Delete an value 4.Exit
Enter your choice:1
Enter the number of elements to be inserted:3 Enter the elements to be inserted:34
45
56
Elements are Inserted into dictionary Sucesfully Enter y to Continue:y
MENU FOR DICTIONARY OPERATIONS:
1. Create
2. Search for a value 3.Delete an value 4.Exit
Enter your choice:2
Enter the element to be searched:45 Search key is found!!
Enter the element to be deleted:56 56 has been deleted.
Elements are Inserted into dictionary Sucesfully Enter y to Continue:y
MENU FOR DICTIONARY OPERATIONS:
1. Create
2. Search for a value 3.Delete an value 4.Exit
Enter your choice:4
Theory:
Binary Search Tree: Binary Search tree is a binary tree in which a left child node
value is less than the Parent node and the right child node value of a node must be
greater than equal to the parent node.
Binary Search Tree: So to make the searching algorithm faster in a binary tree we
will go for building the binary search tree. The binary search tree is based on the
binary search algorithm. While creating the binary search tree the data is
systematically arranged. That means values at left sub-tree < root node value <
right sub-tree values.
main()
{
int ch,y; for(i=1;i<40;i++) tree[i]=-1; while(1)
{
cout <<"1.INSERT\n2.DELETE\n3.DISPLAY\n4.SEARCH\n5.EXIT\nEnter your
choice:"; cin >> ch;
switch(ch)
{
case 1:
cout <<"enter the element to insert"; cin >> ch;
insert(1,ch);
break; case 2:
cout <<"enter the element to delete"; cin >>x;
y=search(1); if(y!=-1) delte(y);
else cout<<"no such element in tree"; break;
case 3:
display(1); cout<<"\n";
for(int i=0;i<=32;i++) cout <<i;
cout <<"\n"; break;
case 4:
cout <<"enter the element to search:"; cin >> x;
y=search(1);
if(y == -1) cout <<"no such element in tree"; else cout <<x << "is in" <<y <<"position";
break;
case 5:
exit(0);
}
}
}
int search(int s)
{
if(t==1)
{
cout <<"no element in tree"; return -1;
}
if(tree[s]==-1) return tree[s]; if(tree[s]>x) search(2*s);
else if(tree[s]<x) search(2*s+1); else
return s;
}
void display(int s)
{
if(t==1)
{cout <<"no element in tree:"; return;}
for(int i=1;i<40;i++) if(tree[i]==-1)
cout <<" ";
else cout <<tree[i]; return ;
Output:
1. INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
enter the element to insert11 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
enter the element to insert22 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
enter the element to insert33 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
enter the element to insert44
1. INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:55 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:1
enter the element to insert55 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:3
11 22 334455
01234567891011121314151617181920212223242526272829303132
1. INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:2
enter the element to delete33 1.INSERT
2. DELETE
3. DISPLAY
4. SEARCH
5. EXIT
Enter your choice:3
11 22 4455
Conclusion: Thus, we have successfully executed the program that performs the
following operations:1. Insert an element in to a binary search tree.
2. Delete an element from a binary search tree.
3. Search for a key element in a binary search tree.