0% found this document useful (0 votes)
15 views83 pages

Lab mannual for DSA for NEP(1)

The document outlines three experiments focused on array manipulation and sorting algorithms in C programming. Experiment 1 covers insertion, deletion, and traversal operations on arrays, while Experiment 2 implements bubble sort, selection sort, and quick sort. Experiment 3 focuses on insertion sort, merge sort, and radix sort, providing algorithms and source code for each sorting method.

Uploaded by

snehal6959
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views83 pages

Lab mannual for DSA for NEP(1)

The document outlines three experiments focused on array manipulation and sorting algorithms in C programming. Experiment 1 covers insertion, deletion, and traversal operations on arrays, while Experiment 2 implements bubble sort, selection sort, and quick sort. Experiment 3 focuses on insertion sort, merge sort, and radix sort, providing algorithms and source code for each sorting method.

Uploaded by

snehal6959
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Date:________________

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

end of the array −


Array - Deletion Operation
In this array operation, we delete an element from the particular index of an array.
This deletion operation takes place as we assign the value in the consequent index
to the current index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
th
K<=N. Following is the algorithm to delete an element available at the K position
of LA.
Array - Traversal Operation
This operation traverses through all the elements of an array. We use loop
statements to carry this out.
Algorithm
Following is the algorithm to traverse through all the elements present in a Linear
Array −

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

The array is: 1 2 3 4 44 5 6 7 8 9 10


Conclusion: Thus, We successfully execute the program that insertion, deletion and
traversing of elements in an array.

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

Selection sort ( Select the smallest and Exchange):


The first item is compared with the remaining n-1 items, and whichever of all is
lowest, is put in the first position. Then the second item from the list is taken and
compared with the remaining (n-2) items, if an item with a value less than that of
the second item is found on the (n-2) items, it is swapped (Interchanged) with the
second item of the list and so on.
Algorithm: Selection_Sort (A[ ] , N)
Step 1 : start Begin
Step 2 : Set POS = K
Step 3 : Repeat for J = K + 1 to N –1 Begin If A[ J ] < A [ POS ] Set POS = J
Step 4 : End For Swap A [ K ] End For with A [ POS ]
Step 5 : Stop
Source code: Program to implement selection sort #include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,min,temp;
clrscr();
printf("\n Enter the Number of
Elements: "); scanf("%d",&n);
printf("\n Enter %d Elements: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
min=j;
}
if(min!=i)
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("\n The Sorted array in ascending
order: "); for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}
Output:
Enter the number of
Elements: 5
Enter 5 Elements:
41936
The stored Array in Ascending
Order: 1 3 4 6 9

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

Conclusion: Thus, We have successfully executed a program that implements the


following sorting i) Bubble sort ii) Selection sort iii) Quick sort.
Experiment No. 3
Aim: Write a program that implements the following i) Insertion sort ii) Merge sort
iii)Radix sort.

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

In a normal Queue Data


Structure, we can insert elements until queue becomes full. But once the queue
becomes full, we can not insert the next element until all the elements are deleted
from the queue after inserting all the elements into it is as follows.
Now consider the following situation after deleting three elements from the 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.

Graphical representation of a circular queue is as follows.


Implementation of Circular Queue
To implement a circular queue data structure using an array, we first perform the
following steps before we implement actual operations.
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 user defined functions used in circular queue implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int cQueue[SIZE])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int
front = -1, rear = -1)
Step 5 - Implement main method by displaying menu of operations list and make
suitable function calls to perform operation selected by the user on circular queue.
1. enQueue(value) - Inserting value into the Circular Queue
In a circular queue, enQueue() is a function which is used to insert an element into
the circular queue. In a circular queue, the new element is always inserted at rear
position. The enQueue() function takes one integer value as parameter and inserts
that value into the circular queue. We can use the following steps to insert an
element into the circular queue.
Step 1 - Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front ==
rear+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 check rear == SIZE - 1 && front != 0 if it is TRUE, then
set rear = -1.
Step 4 - Increment rear value by one (rear++), set queue[rear] = value and check
'front
== -1' if it is TRUE, then set front = 0.
2. deQueue() - Deleting a value from the Circular Queue
In a circular queue, deQueue() is a function used to delete an element from the
circular queue. In a circular queue, the element is always deleted from front
position. The deQueue() function doesn't take any value as a parameter. We can
use the following steps to delete an element from the circular queue...
Step 1 - Check whether queue is EMPTY. (front == -1 && rear == -1)
Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!"
and terminate the function.
Step 3 - If it is NOT EMPTY, then display queue[front] as deleted element and
increment the front value by one (front ++). Then check whether front == SIZE, if it
is TRUE, then set front = 0. Then check whether both front – 1 and rear are equal
(front -1 == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -1).
3. Display() - Displays the elements of a Circular Queue
We can use the following steps to display the elements of a circular queue...
Step 1 - Check whether queue is EMPTY. (front == -1)
Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front'.
Step 4 - Check whether 'front <= rear', if it is TRUE, then display 'queue[i]' value and
increment 'i' value by one (i++). Repeat the same until 'i <= rear' becomes FALSE.
Step 5 - If 'front <= rear' is FALSE, then display 'queue[i]' value and increment 'i'
value by one (i++). Repeat the same until 'i <= SIZE - 1' becomes FALSE.
Step 6 - Set i to 0. Step 7 - Again display 'cQueue[i]' value and increment i value by
one (i++). Repeat the same until 'i <= rear' becomes FALSE
Description:
i) LINEAR SEARCH (SEQUENTIAL SEARCH):
Search begins by comparing the first element of the list with the target element. If it
matches, the search ends. Otherwise, move to next element and compare. In this
way, the target element is compared with all the elements until a match occurs. If
the match do not occur and there are no more elements to be compared, conclude
that target element is absent in the list. Algorithm for Linear search Linear_Search
(A[ ], N, val , pos )
Step 1 : Set pos = -1 and k = 0
Step 2 : Repeat while k < N Begin
Step 3 : if A[ k ] = val Set pos = k print pos Goto step 5 End while
Step 4 : print “Value is not present”
Step 5 : Exit
(ii)Binary Search: Before searching, the list of items should be sorted in ascending
order. First compare the key value with the item in the mid position of the array. If
there is a match, we can return immediately the position. if the value is less than
the element in middle location of the array, the required value is lie in the lower half
of the array. If the value is greater than the element in middle location of the array,
the required value is lie in the upper half of the array. We repeat the above
procedure on the lower half or upper half of the array. Algorithm: Binary_Search (A
[ ], U_bound, VAL)
Step 1 : set BEG = 0 , END = U_bound , POS = -1
Step 2 : Repeat while (BEG <= END ) Step 3 :set MID = ( BEG + END ) / 2 POS = MID
print VAL “ is available at “, POS GoTo Step 6 End if
if A [ MID ] > VAL then set END = MID – 1 Else set BEG = MID + 1
End if End while
Step 5 : if POS = -1 then print VAL “ is not present “ End if
Step 6 : EXIT
Source Code: To implement Circular Queue using Arrays. #include<iostream.h>
#include<conio.h> #define SIZE 5 void enQueue(int); void deQueue(); void display();
int cQueue[SIZE],front = -1, rear = -1; void main()
{
int choice, value; clrscr();
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n"); printf("Enter your choice: ");
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf("\nEnter the value to be insert: "); scanf(“%d”,&value);
enQueue(value); break;
case 2: deQueue();
break; case 3:display();
break; case 4: exit(0);
default: printf("\nPlease select the correct choice!!!\n");
}
}
}
void enQueue(int value)
{
if((front == 0 && rear == SIZE - 1) || (front == rear+1)) printf("\nCircular Queue is
Full! Insertion not possible!!!\n"); else
{
if(rear == SIZE-1 && front != 0) rear = -1; cQueue[++rear] = value;
printf("\nInsertion Success!!!\n"); if(front == -1) front = 0;
}
}
void deQueue()
{
if(front == -1 && rear == -1)
printf("\nCircular Queue is Empty! Deletion is not possible!!!\n"); else
{
printf("\nDeleted element :%d",cQueue[front++]);
if(front == SIZE) front = 0;
if(front-1 == rear) front = rear = -1;
}
}
void display()
{
if(front == -1)
printf("\nCircular Queue is Empty!!!\n"); else
{
int i = front;
printf("\nCircular Queue Elements are : \n"); if(front <= rear)
{
while(i <= rear) printf(”%d\t”, cQueue[i++]);
}
else
{
while(i <= SIZE - 1) printf(”%d\t”, cQueue[i++]); i = 0;
while(i <= rear) printf(”%d\t”, cQueue[i++]);
}
}
}
OUTPUT:
1.Insert element to queue 2.Delete element from queue 3.Display all elements of
queue 4.Quit
Enter your choice : 1
Inset the element in queue : 10 1.Insert element to queue 2.Delete element from
queue 3.Display all elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 15
1.Insert element to queue 2.Delete element from queue 3.Display all elements of
queue 4.Quit
Enter your choice : 1
Inset the element in queue : 20 1.Insert element to queue 2.Delete element from
queue 3.Display all elements of queue 4.Quit
Enter your choice : 1
Inset the element in queue : 30 Enter your choice : 4
Source code: Non recursive and recursive C++ program for Linear search
#include <stdio.h>
#include <conio.h>
#define MAX_LEN 10
void l_search_recursive(int l[],int num,intele);
void l_search_nonrecursive(int l[],int num,intele);
void read_list(int l[],int num);
void print_list(int l[],int num);
int main()
{
int l[MAX_LEN], num, ele; int ch;
printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Linear Search using Recursion method"); printf("\n[2] Linear Search
using Non-Recursion method"); printf("\n\n Enter your Choice:");
scanf("%d",&ch);
if(ch<=2 &ch>0)
{
printf("Enter the number of elements :");
scanf("%d",&num);
read_list(l,num);
printf("\nElements present in the list are:\n\n");
print_list(l,num);
printf("\n\nElement you want to search:\n\n");
scanf("%d",&ele);
switch(ch)
{
case 1:
printf("\n**Recursion method**\n");
l_search_recursive(l,num,ele); getch();
break;
case 2:
printf("\n**Non-Recursion method**\n");
l_search_nonrecursive(l,num,ele);
getch();
break;
}
}
getch();
}
void l_search_nonrecursive(int l[],int num,intele)
{
int j, f=0;
for(j=0; j<num; j++) if( l[j] == ele)
{
printf("\nThe element %d is present at position %d in list\n",ele,j); f=1;
break;
}
if(f==0)
printf("\nThe element is %d is not present in the list\n",ele);
}
void l_search_recursive(int l[],int num,intele)
{
int f = 0;
if( l[num] == ele)
{
printf("\nThe element %d is present at position %d in list\n",ele,num); f=1;
}
else
{
if((num==0) && (f==0))
{
printf("The element %d is not found.",ele);
}
else
{
l_search_nonrecursive(l,num-1,ele);
}
}
getch();
}
void read_list(int l[],int num)
{
int j;
printf("\nEnter the elements:\n"); for(j=0; j<num; j++) scanf("%d",&l[j]);
}
void print_list(int l[],int num)
{
int j;
for(j=0; j<num; j++) printf("%d\t",l[j]);
}
OUTPUT:
====================================================== MENU
=====================================================
[1] Linear Search using Recursion method
[2] Linear Search using Non-Recursion method Enter your Choice:1
Enter the number of elements : 5 Enter the elements:
12
22
32
42
52
Elements present in the list are:
12 22 32 42 52
Enter the element you want to search:
42
Recursive method:
Element is found at 3 position
Source code: Recursive and non Recursive C++ program for binary search
#include <stdio.h>
#define MAX_LEN 10
void b_search_nonrecursive(int l[],int num,intele)
{
int l1,i,j, flag = 0; l1 = 0;
i = num-1;
while(l1 <= i)
{
j = (l1+i)/2; if( l[j] == ele)
{
printf("\nThe element %d is present at position %d in list\n",ele,j);
flag =1;
break;
}
else
if(l[j] <ele) l1 = j+1;
else
i = j-1;
}
if( flag == 0)
printf("\nThe element %d is not present in the list\n",ele);
}
/* Recursive function*/
int b_search_recursive(int l[],int arrayStart,intarrayEnd,int a)
{
int m,pos;
if (arrayStart<=arrayEnd)
{
m=(arrayStart+arrayEnd)/2; if (l[m]==a)
return m;
else if (a<l[m])
return b_search_recursive(l,arrayStart,m-1,a); else
return b_search_recursive(l,m+1,arrayEnd,a);
}
return -1;
}
void read_list(int l[],int n)
{
int i;
printf("\nEnter the elements:\n"); for(i=0;i<n;i++) scanf("%d",&l[i]);
}
void print_list(int l[],int n)
{
int i; for(i=0;i<n;i++) printf("%d\t",l[i]);
}
/*main function*/ main()
{
int l[MAX_LEN], num, ele,f,l1,a; int ch,pos;
//clrscr();
printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Binary Search using Recursion method"); printf("\n[2] Binary Search
using Non-Recursion method"); printf("\n\nEnter your Choice:");
scanf("%d",&ch); if(ch<=2 &ch>0)
{
printf("\nEnter the number of elements : "); scanf("%d",&num);
read_list(l,num);
printf("\nElements present in the list are:\n\n"); print_list(l,num);
printf("\n\nEnter the element you want to search:\n\n");
scanf("%d",&ele);
switch(ch)
{
case 1:printf("\nRecursive method:\n"); pos=b_search_recursive(l,0,num,ele);
if(pos==-1)
{
printf("Element is not found");
}
else
{
printf("Element is found at %d position",pos);
}
//getch(); break;
case 2:printf("\nNon-Recursive method:\n"); b_search_nonrecursive(l,num,ele);
//getch(); break;
}
}
//getch();
}
OUTPUT:
====================================================== MENU
=====================================================
[1] Binary Search using Recursion method
[2] Binary Search using Non-Recursion method
Enter your Choice:1
Enter the number of elements : 5 Enter the elements:
12
22
32
42
52
Elements present in the list are:
12 22 32 42 52
Enter the element you want to search:
42
Recursive method:
Element is found at 3 position

Conclusion: Thus, we have successfully execute the 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.
Experiment No. 4
Aim: Write a program that uses functions to perform the following operations on
singly linked list i) Creation ii) Insertion iii) Deletion iv)Traversal.
Objective: The objective of the practical is to implement the following operations
on Singly Linked List as
i. Creation of Singly Linked List
ii. Insertion of new element into the Linked List
iii. Deletion of element from the Linked List
iv.Traversal of the Linked list
Theory:
When we want to work with an unknown number of data values, we use a linked
list data structure to organize that data. The linked list is a linear data structure
that contains a sequence of elements such that each element links to its next
element in the sequence. Each element in a linked list is called "Node".
Linked List can be implemented as
1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List
Single Linked List
Simply a list is a sequence of data, and the linked list is a sequence of data linked
with each other. The formal definition of a single linked list is as follows...
In any single linked list, the individual element is called as "Node". Every "Node"
contains two fields, data field, and the next field. The data field is used to store
actual value of the node and next field is used to store the address of next node in
the sequence. The graphical representation of a node in a single linked list is as
follows...

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

2.1 Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the single
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, set newNode! next = NULL and head =
newNode.
Step 4 - If it is Not Empty then, set newNode! next = head and head =
newNode.

2.2 Inserting At End of the list


We can use the following steps to insert a new node at end of the single 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, set head = newNode.
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 - Set temp ! next = newNode.

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 single
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, set newNode ! next = NULL and head =


newNode.
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
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 temp is reached to last node or not. If
it is reached to last node then display 'Given node is not found in
the list!!! Insertion not possible!!!' and terminate the function.
Otherwise move the temp to next node.
Step 7 - Finally, Set 'newNode ! next = temp ! next' and 'temp ! next =
newNode'

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

3.1 Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the single
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 ! next == NULL)
Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty
list conditions)
Step 6 - If it is FALSE then set head = temp ! next, 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 single 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 two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 ! next == NULL)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And
terminate 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 it reaches to the last
node in the list. (until temp1 ! next ==
NULL)
Step 7 - Finally, Set temp2 ! next = NULL 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 single
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 two Node pointers 'temp1' and
'temp2' and
initialize 'temp1' with head.
Step 4 - Keep moving the temp1 until it reaches to the exact node to be
deleted or to the last node. And every time set 'temp2 = temp1'
before moving the 'temp1' to its next 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 to
be deleted, then set head = NULL and delete
temp1 (free(temp1)).
Step 8 - If list contains multiple nodes, then check whether temp1 is the
first node in the list (temp1 == head).
Step 9 - If temp1 is the first node then move the head to the next
node (head = head ! next) and delete temp1.
Step 10 - If temp1 is not first node then check whether it is last
node in the list (temp1 ! next == NULL).
Step 11 - If temp1 is last node then set temp2 !
next = NULL and delete temp1
(free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 !
next = temp1 ! next and delete temp1 (free(temp1)).
4. Displaying a Single Linked List
We can use the following steps to display the elements of a single 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 - Keep displaying temp ! data with an arrow (--->) until temp
reaches to the last node
Step 5 - Finally display temp ! data with arrow pointing to NULL (temp !
data ---> NULL).
Program:

#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:

Conclusion: Thus, We successfully execute the program that uses functions to


perform the following operations on singly linked list i) Creation ii) Insertion iii)
Deletion iv)Traversal.
Date:_____________
Experiment No.5
Aim: Write a program that uses functions to perform the following operations on
doubly linked List (i)Creation (ii) Insertion (iii) Deletion (iv) Traversal.
Objective: The objective of the practical is to implement the following operations
on doubly Linked List as
i.Creation of Singly Linked List
ii. Insertion of new element into the Linked List
iii. Deletion of element from the Linked List
iv. Traversal of the Linked list
Theory:
Double Linked List
In a single linked list, every node has a link to its next node in the sequence. So, we
can traverse from one node to another node only in one direction and we can not
traverse back. We can solve this kind of problem by using a double linked list. A
double linked list can be defined as follows.
Double linked list is a sequence of elements in which every element has links to its
previous element and next element in the sequence
In a double linked list, every node has a link to its previous node and next node. So,
we can traverse forward by using the next field and can traverse backward by using
the previous field. Every node in a double linked list contains three fields and they
are shown in the following figure.

Here, 'link1' field is used to store the address of the previous


node in the sequence, 'link2' field is used to store the address of the next node in
the sequence and 'data' field is used to store the actual value of that node.

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).

Source Code: To implement Doubly Linked List


#include<iostream.h>
#include<conio.h>
void insertAtBeginning(int);
void insertAtEnd(int);
void insertAtAfter(int,int);
void deleteBeginning();
void deleteEnd();
void deleteSpecific(int);
void display();
struct Node
{
int data;
struct Node *previous, *next;
}*head = NULL;
void main()
{
int choice1, choice2, value, location;
clrscr();
while(1)
{
printf("\n*********** MENU *************\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\nEnter your choice: ");
scanf(“%d”,&choice1);
switch(choice1)
{
case 1: printf("Enter the value to be inserted: ");
scanf(“%d”, &value);
while(1)
{
printf("\nSelect from the following Inserting options\n");
printf("1.At Beginning\n2.AtEnd\n3.After a Node\n4. Cancel\nEnter your
choice:");
scanf(“%d”,&choice2);
switch(choice2)
{
case1:insertAtBeginning(value);
break;
case 2: insertAtEnd(value);
break;
case 3: printf("Enter the location after which you want to insert:");
scanf(“%d”,&location);
insertAfter(value,location);
break;
case 4: goto EndSwitch;
default: printf("\nPlease select correct Inserting option!!!\n");
}
}
case 2: while(1)
{
printf("\nSelect from the following Deleting options\n");
printf("1. At Beginning\n2. At End\n3. Specific Node\n4.
Cancel\nEnter your choice: "); scanf(“%d”,&choice2);
switch(choice2)
{
case 1: deleteBeginning();
break;
case 2: deleteEnd();
break;
case 3: printf("Enter the Node value to be deleted: ");
scanf(“%d”,&location);
deleteSpecic(location);
break;
case 4: goto EndSwitch;
default: printf("\nPlease select correct Deleting option!!!\n");
}
}
EndSwitch: break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nPlease select correct option!!!");
}
}
}
void insertAtBeginning(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
newNode -> previous = NULL;
if(head == NULL)
{
newNode -> next = NULL;
head = newNode;
}
else
{
newNode -> next = head;
head = newNode;
}
printf("\nInsertion success!!!");
}
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
newNode -> next = NULL;
if(head == NULL)
{
newNode -> previous = NULL;
head = newNode;
}
else
{
struct Node *temp = head;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newNode;
newNode -> previous = temp;
}
printf("\nInsertion success!!!");
}
void insertAfter(int value, int location)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = value;
if(head == NULL)
{
newNode -> previous = newNode -> next = NULL;
head = newNode;
}
else
{
struct Node *temp1 = head, temp2;
while(temp1 -> data != location)
{
if(temp1 -> next == NULL)
{
printf("Given node is not found in the list!!!");
goto EndFunction;
}
else { temp1 = temp1 -> next;
}
} temp2 = temp1 -> next; temp1 -> next = newNode;
newNode -> previous = temp1;
newNode -> next = temp2;
temp2 -> previous = newNode;
printf(“\nInsertion success!!!");
}
EndFunction:
}
void deleteBeginning()
{
if(head == NULL)
printf("List is Empty!!! Deletion not possible!!!");
else {
struct Node *temp = head;
if(temp -> previous == temp -> next)
{
head = NULL;
free(temp);
}
else
{
head = temp -> next;
head -> previous = NULL;
free(temp);
}
print"\nDeletion success!!!");
}
}
void deleteEnd()
{
if(head == NULL)
printf(”List is Empty!!! Deletion not possible!!!");
else
{
struct Node *temp = head;
if(temp -> previous == temp -> next) {
head = NULL;
free(temp);
}
else
{
while(temp -> next != NULL)
temp = temp -> next;
temp -> previous -> next = NULL;
free(temp);
}
printf("\nDeletion success!!!");
}
}
void deleteSpecific(int delValue)
{
if(head == NULL)
printf("List is Empty!!! Deletion not possible!!!");
else
{
struct Node *temp = head;
while(temp -> data != delValue)
{
if(temp -> next == NULL)
{
printf("\nGiven node is not found in the list!!!");
goto FuctionEnd;
}
else
{
temp = temp -> next;
}
}
if(temp == head)
{
head = NULL;
free(temp);
}
else
{
temp -> previous -> next = temp -> next;
free(temp);
}
printf("\nDeletion success!!!");
}
FuctionEnd:
}
void display()
{
if(head == NULL)
printf("\nList is Empty!!!");
else
{
struct Node *temp = head;
printf("\nList elements are: \n");
printf("NULL <--- ");
while(temp -> next != NULL)
{
printf(“%d”,temp -> data”\t”);
}
printf(“%d”, temp -> data);
}
}
Output:

Conclusion: Thus, We successfully execute the program that uses functions to


perform the following operations on doubly linked List (i)Creation (ii) Insertion (iii)
Deletion (iv) Travers
Date:

Experiment No. 6

Aim: Write a program that uses functions to perform the following


operations on circular linked List
(i)Creation (ii) Insertion (iii) Deletion (iv) Traversal.

Theory:

Circular Linked List


In single linked list, every node points to its next node in the sequence and the
last node points NULL. But in circular linked list, every node points to its next
node in the sequence but the last node points to the first node in the list.
A circular linked list is a sequence of elements in which every element has a link to its
next element in the sequence and the last element has a link to the first element.

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

data and next Step 2 - Define a Node pointer 'head'

and set it to NULL.


2.Insertion
In a circular 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

2.1 Inserting At Beginning of the list


We can use the following steps to insert a new node at beginning of the
circular 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, set head = newNode and newNode! next =


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 (until 'temp ! next == head').

Step 6 - Set 'newNode ! next =head', 'head = newNode' and 'temp ! next
= head'.

2.2 Inserting At End of the list


We can use the following steps to insert a new node at end of the circular
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, set head = newNode and newNode !
next = 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 == head).
Step 6 - Set temp ! next = newNode and newNode ! next = head.
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 circular
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, set head = newNode and newNode !
next = 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 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 temp is reached to the last node or
not. If it is reached to last node then display 'Given node is not
found in the list!!! Insertion not possible!!!' and terminate the
function. Otherwise move the temp to next node.
Step 7 - If temp is reached to the exact node after which we want to
insert the newNode then check whether it is last node (temp !
next == head).
Step 8 - If temp is last node then set temp ! next = newNode
and newNode ! next = head.
Step 9 - If temp is not last node then set newNode ! next = temp ! next
and temp ! next = newNode.
3. Deletion
In a circular linked list, the deletion operation can be performed in three ways
those 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

3.1 Deleting from Beginning of the list


We can use the following steps to delete a node from beginning of the circular
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 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 6 - If it is FALSE move the temp1 until it reaches to


the last node. (until temp1 ! next == head )
Step 7 - Then set head = temp2 ! next, temp1 ! next = head and delete
temp2.

3.2 Deleting from End of the list


We can use the following steps to delete a node from end of the circular 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 two Node pointers 'temp1' and
'temp2' and initialize 'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 ! next == head)

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 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 two Node pointers 'temp1'


and 'temp2' and initialize 'temp1' with head.
Step 4 - Keep moving the temp1 until it reaches to the exact node to be
deleted or to the last node. And every time set 'temp2 = temp1'
before moving the 'temp1' to its next 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 (temp1 ! next==
head)
Step 7 - If list has only one node and that is the node to
be deleted then set head = NULL and delete
temp1 (free(temp1)).
Step 8 - If list contains multiple nodes then check whether temp1 is the
first node in the list (temp1 == head).
Step 9 - If temp1 is the first node then set temp2 = head and keep
moving temp2 to its next node until temp2 reaches to the last
node. Then set head = head !
next, temp2 ! next = head and delete temp1.

Step 10 - If temp1 is not first node then check whether it is last


node in the list (temp1 ! next == head).
Step 1 1- If temp1 is last node then set temp2 !
next = head and delete temp1
(free(temp1)).
Step 12 - If temp1 is not first node and not last node then set

temp2 ! next = temp1 ! next and delete temp1


(free(temp1)).
4.Displaying a Circular Linked List
We can use the following steps to display the elements of a circular 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 - Keep displaying temp ! data with an arrow (--->) until temp
reaches to the last node

Step 5 - Finally display temp ! data with arrow pointing to head


! data.
Source Code: To implement Circular Linked List.
#include<i
ostream.h
>
#include<
conio.h>
void
insertAtBeginni
ng(int); void
insertAtEnd(int);
void
insertAtAfter(i
nt,int); void
deleteBeginnin
g(); void
deleteEnd();
void
deleteSpeci
fic(int); void
display();

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;

case 4:goto EndSwitch;


default: cout<<"\nPlease select correct Inserting option!!!
\n";
}
}
case 2: while(1)
{
cout<<"\nSelect from the following Deleting
options\n"; cout<<"1. At Beginning\n2. At
End\n3. Specific Node\n4.
Cancel\nEnter your choice:
"; cin>>choice2;
switch(choice2)
{
case 1: deleteBeginning();
break;
case 2: deleteEnd();
break;
case 3: cout<<"Enter the Node value to be
deleted: "; cin>>location;
deleteSpecic(l
ocation);
break;
case 4: goto EndSwitch;
default: cout<<"\nPlease select correct Deleting
option!!!\n";

}
}

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)
{

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 ->
data != location)
{
if(temp -> next == head)
{
cout<<"Given node is not found in the list!!!";
goto EndFunction;
}
else
{
temp = temp -> next;
}
}
newNode -> next = temp
-> next; temp -> next =
newNode;
cout<<"\nInsertion
success!!!";
}
EndFunction:
}
void deleteBeginning()
{
if(head == NULL)
cout<<"List is Empty!!! Deletion not possible!!!";
else
{
struct Node *temp = head;

if(temp -> next == head)


{
head = NULL;
free(temp);
}
else
{
head =
head ->
next;
free(temp);

}
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;

temp1 = temp1 -> next;

}
}
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";

while(temp -> next != head)


{
cout<<temp -> data;
}
cout<< temp -> data, head -> data;
}
}

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.

In a stack, the insertion operation is performed using a function called


"push" and deletion operation is performed using a function called "pop".
In the figure, PUSH and POP operations are performed at a top position in
the stack. That means, both the insertion and deletion operations are performed
at one end (i.e., at Top).
A stack data structure can be defined as follows.
Stack is a linear data structure in which the operations are performed based
on LIFO principle.
Stack can also be defined as
"A Collection of similar data items in which both insertion and deletion
operations are performed based on LIFO principle".
Example

If we want to create a stack by inserting 10,45,12,16,35 and


50. Then 10 becomes the bottom-most element and 50 is the topmost element.
The last inserted element 50 is at Top of the stack as shown in the image below
Operations on a Stack
The following operations are performed on the stack
1. Push (To insert an element on to the stack)
2. Pop (To delete an element from the stack)
3. Display (To display elements of the stack)
Stack data structure can be implemented in two ways. They are as follows
1. Using Arrays
2. Using Linked List
Stack Using Arrays
A stack data structure can be implemented using a one-dimensional array. But
stack implemented using array stores only a fixed number of data values. This
implementation is very simple. Just define a one dimensional array of specific size
and insert or delete the values into that array by using LIFO principle with the help
of a variable called 'top'.
Initially, the top is set to -1. Whenever we want to insert a value into the
stack, increment the top value by one and then insert. Whenever we want to
delete a value from the stack, then delete the top value and decrement the top
value by one.
Stack Operations
We can Perform the following Operations on Stack
1. Push()
2. Pop()
3. Display()
A stack can be implemented using array as follows.
Before implementing actual operations, first follow the below steps to create an
empty stack
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 functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make suitable
function calls to perform operation selected by the user on the stack.
1. Push(value) - Inserting value into the stack
In a stack, push() is a function used to insert an element into the stack. In a stack,
the new element is always inserted at top position. Push function takes one integer
value as parameter and inserts that value into the stack.
We can use the following steps to push an element on to the stack.
Step 1 - Check whether stack is FULL. (top == SIZE-1)
Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3 - If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
2. Pop() - Delete a value from the Stack
In a stack, pop() is a function used to delete an element from the stack. In a stack,
the element is always deleted from top position. Pop function does not take any
value as parameter. We can use the following steps to pop an element from the
stack
Step 1 - Check whether stack is EMPTY. (top == -1)
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!"
and terminate the function.
Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one
(top--).
1.Display() - Displays the Elements of a Stack
We can use the following steps to display the elements of a stack.
Step 1 - Check whether stack is EMPTY. (top == -1)
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
Step 4 - Repeat above step until i value becomes '0'.
(ii) Stack Using Linked List
The major problem with the stack implemented using an arrays is, it works
only for a fixed number of data values. That means the amount of data must be
specified at the beginning of the implementation itself.
Stack implemented using an array is not suitable, when we don't know the
size of data which we are going to use. A stack data structure can be implemented
by using a linked list data structure.
The stack implemented using linked list can work for an unlimited number
of values.
That means, stack implemented using linked list works for the variable size
of data. So, there is no need to fix the size at the beginning of the implementation.
The Stack implemented using linked list can organize as many data values as we
want.
In linked list implementation of a stack, every new element is inserted as
'top' element. That means every newly inserted element is pointed by 'top'.
Whenever we want to remove an element from the stack, simply remove the node
which is pointed by 'top' by moving 'top' to its previous node in the list. The next
field of the first element must be always NULL.
Example
In the above example, the last inserted node is 99 and the first inserted node is
25. The order of elements inserted is 25, 32,50 and 99.
Stack Operations using Linked List
We can Perform the Following Operations on Stack Using Linked List (i.e)
1. Push()
2. Pop()
3. Display()
To implement a stack using a 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 a Node pointer 'top' and set it to NULL.
Step 4 - Implement the main method by displaying Menu with list of
operations and make suitable function calls in the mainmethod.
1.Push(value) - Inserting an element into the Stack
We can use the following steps to insert a new node into the stack...
Step 1 - Create a newNode with given value.
Step 2 - Check whether stack is Empty (top == NULL)
Step 3 - If it is Empty, then set newNode ! next = NULL.
Step 4 - If it is Not Empty, then set newNode ! next = top.
Step 5 - Finally, set top = newNode.
2.Pop() - Deleting an Element from a Stack
We can use the following steps to delete a node from the stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not
possible!!!" and terminate the function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top ! next'.
Step 5 - Finally, delete 'temp'. (free(temp)).

3.Display() - Displaying stack of elements


We can use the following steps to display the elements (nodes) of a stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the
function.
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize
with top.
Step 4 - Display 'temp ! data --->' and move it to the next node. Repeat the
same until temp reaches to the first node in the stack. (temp ! next !=
NULL).
Step 5 - Finally! Display 'temp ! data ---> NULL

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:

Source Code: To Implement Stack Using Linked List


#include<stdio.h>
#include<iostream.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}
*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter 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!!! Please try again!!!\n");
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct Node *temp = top;
printf("\nDeleted element:",temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct Node *temp = top;
while(temp->next != NULL)
printf("%d", temp->data);
temp = temp -> next;
}
printf("%d",temp->data);
}
}
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...

Step 1 - Check whether queue is EMPTY. (front == rear)


Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!"
and terminate the function.
Step 3 - If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether
both front and rear are equal (front == rear), if it TRUE, then set both front and rear
to '-1' (front = rear = -1).
3.Display() - Displays the elements of a Queue
We can use the following steps to display the elements of a queue
Step 1 - Check whether queue is EMPTY. (front == rear)
Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front+1'.
Step 4 - Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the
same until 'i' value reaches to rear (i <= rear).
Queue Using Linked List
The major problem with the queue implemented using an array is, It will work for
an only fixed number of data values. That means, the amount of data must be
specified at the beginning itself. Queue using an array is not suitable when we
don't know the size of data which we are going to use.
A queue data structure can be implemented using a linked list data structure. The
queue which is implemented using a linked list can work for an unlimited number
of values. That means, queue using linked list can work for the variable size of
data (No need to fix the size at the beginning of the implementation).
The Queue implemented using linked list can organize as many data values as we
want. In linked list implementation of a queue, the last inserted node is always
pointed by 'rear' and the first node is always pointed by 'front'.
Example

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.

2.deQueue() - Deleting an Element from Queue


We can use the following steps to delete a node from the queue...

Step 1 - Check whether queue is Empty (front == NULL).


Step 2 - If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!"
and terminate from the function
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4 - Then set 'front = front ! next' and delete 'temp' (free(temp)).

3.Display() - Displaying the elements of Queue


We can use the following steps to display the elements (nodes) of a queue...
Step 1 - Check whether queue is Empty (front == NULL).
Step 2 - If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4 - Display 'temp ! data --->' and move it to the next node. Repeat the same
until 'temp' reaches to 'rear' (temp ! next != NULL).
Step 5 - Finally! Display 'temp ! data ---> NULL'
Program:
Source Code: To implement Queue using Arrays
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
int queue[SIZE], front = -1, rear = -1;
void main()
{
int value, choice; clrscr();
while(1)
{
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\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);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4:exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void enQueue(int value)
{
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else
{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue()
{
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display()
{
if(rear == -1)
printf("\nQueue is Empty!!!");
else
{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d", queue[i]);
}
}
Output:
Source Code: To implement Queue using Linked List
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}
*front = NULL,*rear = NULL;
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf(choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
insert(value);
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else
{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL)
{
printf("%d",temp->data);
temp = temp -> next;
}
printf("%d",temp->data);
}
}
Output:
Conclusion: Thus, we have successfully execute the program that implement
Queue (its operations) using (i)Arrays (ii)Linked list(Pointers).

Experiment No. 9

Aim: Write a program to implement all the functions of a dictionary(ADT)using


Linked List.

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.

Source code: To to implement all the functions of a dictionary (ADT)


#include<iostream>
//#include<conio>
#include<stdlib.h>
using namespace std;
# define max 10 typedef
struct list
{
int data;
struct list *next;
} node_type;
node_type *ptr[max],*root[max],*temp[max]; class Dictionary
{
public:
int index; Dictionary(); void insert(int); void search(int);
void delete_ele(int);
};
Dictionary::Dictionary()
{
index=-1;
for(int i=0; i<max; i++)
{
root[i]=NULL; ptr[i]=NULL; temp[i]=NULL;
}
}
void Dictionary::insert(int key)
{
index=int(key%max); ptr[index]=(node_type*)malloc(sizeof(node_type)); ptr[index]-
>data=key;
if(root[index]==NULL)
{
root[index]=ptr[index]; root[index]->next=NULL; temp[index]=ptr[index];
}
else
{
temp[index]=root[index]; while(temp[index]->next!=NULL)
temp[index]=temp[index]->next; temp[index]->next=ptr[index];
}
}
void Dictionary::search(int key)
{
int flag=0; index=int(key%max); temp[index]=root[index]; while(temp[index]!=NULL)
{
if(temp[index]->data==key)
{
cout<<"\nSearch key is found!!"; flag=1;
break;
}
else temp[index]=temp[index]->next;
}
if (flag==0)
cout<<"\nsearch key not found";
}
void Dictionary::delete_ele(int key)
{
index=int(key%max); temp[index]=root[index];
while(temp[index]->data!=key && temp[index]!=NULL)
{
ptr[index]=temp[index]; temp[index]=temp[index]->next;
}
ptr[index]->next=temp[index]->next; cout<<"\n"<<temp[index]->data<<" has been
deleted."; temp[index]->data=-1;
temp[index]=NULL; free(temp[index]);
}
int main()
{
int val,ch,n,num; char c; Dictionary d;
do
{
cout<<"\nMENU FOR DICTIONARY OPERATIONS:\n1.Create";
cout<<"\n2.Search for a value\n3.Delete an value"; cout<<"\nEnter your choice:";
cin>>ch; switch(ch)
{
case 1:
cout<<"\nEnter the number of elements to be inserted:"; cin>>n;
cout<<"\nEnter the elements to be inserted:"; for(int i=0; i<n; i++)
{
cin>>num; d.insert(num);
}
break; case 2:
cout<<"\nEnter the element to be searched:"; cin>>n;
d.search(n); case 3:
cout<<"\nEnter the element to be deleted:"; cin>>n;
d.delete_ele(n); break;
default:
cout<<"\nInvalid Choice.";
}
cout<<"\n Elements are Inserted into dictionary Sucesfully"; cout<<"\nEnter y to
Continue:";
cin>>c;
}
while(c=='y');
//getch();
}

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

Conclusion: Thus, we have successfully executed a program that implements all


the functions of a dictionary (ADT) using Linked List.
Experiment No.10

Aim: Write a program to perform 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.

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.

Source code: To implement Binary Search tree #include<iostream>


//#include<conio.h> #include<stdlib.h> using namespace std;

void insert(int,int ); void delte(int); void display(int); int search(int);


int search1(int,int); int tree[40],t=1,s,x,i;

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);
}
}
}

void insert(int s,int ch )


{
int x; if(t==1)
{
tree[t++]=ch; return;
}
x=search1(s,ch); if(tree[x]>ch) tree[2*x]=ch; else tree[2*x+1]=ch; t++;
}
void delte(int x)
{

if( tree[2*x]==-1 && tree[2*x+1]==-1) tree[x]=-1;


else if(tree[2*x]==-1)
{tree[x]=tree[2*x+1]; tree[2*x+1]=-1;
}
else if(tree[2*x+1]==-1)
{tree[x]=tree[2*x]; tree[2*x]=-1;
}
else
{
tree[x]=tree[2*x]; delte(2*x);
}
t--;
}

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 ;

int search1(int s,int ch)


{
if(t==1)
{
cout <<"no element in tree"; return -1;
}
if(tree[s]==-1) return s/2; if(tree[s] > ch) search1(2*s,ch);
else search1(2*s+1,ch);
}

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.

You might also like