You are on page 1of 141

DEBRE MARKOS UNIVERSITY

INSTITUTE OF TECHNOLOGY

SCHOOL OF COMPUTING

INFORMATION TECHNOLOGY ACADEMIC PROGRAM

LAB MANUAL

Program: Undergraduate
Course Code: ITec2052
Year: Two
Course Title: Data Structure and Algorithm

Programming Language: Python

Prepared By:
Minalu Chalie (MSc)
Information Technology Academic Program

i
Table of Contents
UNIT ONE Search and Sort Algorithm..........................................................................................2

1. Simple Sorting and Searching Algorithms...............................................................................2

1.1. Searching Algorithm.........................................................................................................2

1.1.1. Linear search..............................................................................................................2

1.1.2. Binary search.............................................................................................................6

1.2. Sort algorithm.................................................................................................................11

1.2.1 Insertion sort............................................................................................................11

1.2.1. Selection sort...........................................................................................................14

1.2.2. Bubble sort...............................................................................................................16

UNIT TWO Linked lists.............................................................................................................19

2. Creating Linked Lists.............................................................................................................19

2.1. Singly Linked List...........................................................................................................19

2.1.1. How it works............................................................................................................19

2.2. Double linked list............................................................................................................35

2.2.1. How it works............................................................................................................35

2.3. Circular Single Linked List:...............................................................................................50

2.4. Circular Double Linked List...............................................................................................69

UNIT THREE Stack...................................................................................................................86

3. Stack Implementation.............................................................................................................86

3.1. Array implementation of stack........................................................................................86

3.1.1. Pop operation...........................................................................................................86

3.1.2. Push operation.........................................................................................................86

3.2. Stack as linked list...........................................................................................................92

3.2.1. Push operation:........................................................................................................92

ii
3.2.2. Pop operation:..........................................................................................................92

3.3. Algorithm to convert an infix to postfix expression........................................................95

UNIT FOUR Queue..................................................................................................................100

4. Queue implementations........................................................................................................100

4.1. Array implementation of enqueue and dequeue operation...........................................100

4.2. Circular array implementation of enqueue and dequeue..............................................104

4.3. Double ended queue using linked list...........................................................................109

UNIT FIVE Binary search tree...................................................................................................118

5. Binary search tree.................................................................................................................118

5.1. Implementation of binary search tree............................................................................118

5.2. Traverse.........................................................................................................................123

UNIT SIX Advanced Sorting and Searching Algorithms.......................................................129

6.1. Quick sort..................................................................................................................129

6.2. Heap sort....................................................................................................................132

6.3. Merge sort..................................................................................................................135

iii
Objectives of Lab Manual
Upon the completion of Data Structures practical course, the student will be able to:
 Design and analyze the time and space efficiency of the data structure.
 Develop the appropriate data structure for given problem.
 Determining the applications of data structures.
 Choose the appropriate data structure and algorithm design method for a specified
application.
 Defining which algorithm or data structure to use in different scenarios.
 Define and apply fundamental algorithmic problems including Tree traversals, Graph
traversals.
 Compare different implementations of data structures and to recognize the advantages
and disadvantages of them.
 Write complex applications using structured programming methods.

UNIT ONE
1
Search and Sort Algorithm

1. Simple Sorting and Searching Algorithms


1.1. Searching Algorithm
In search algorithm which solves the search problem, namely, to retrieve information stored
within some data structure, or calculated in the search space of a problem domain.

Well, to search an element in a given array, there are two popular algorithms available:

 Linear Search
 Binary Search

1.1.1. Linear search


Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.
Linear Search Algorithm

1. Start
2. Input array
3. Input search_element
4. i <- 0
5. While i < = length of array do
i. If search_element = array [ i ] then
a. Return i
ii. EndIf
iii. i <- i + 1
6. EndWhile
7. Return -1
8. Stop

Source code:
//Using one dimensional array
#include<iostream.h>
#include<conio.h>
int main()
{

2
int *list;
int i,item,flag=0,n;
cout<<"Enter size of array element\n";//The maximum size is array size
cin>>n;
list=new int[n];
cout<<"Enter the data in the array\n";
for(i=0;i<n;i++)
{
cin>>list[i];
}
cout<<"Enter the element to be searched\n";
cin>>item;
for(i=0;i<n;i++)
{
if(item==list[i])
{
flag=1;
break;
}
}
if(flag==0)
cout<<"Element not found";
else
cout<<"Element found at position "<<i;
getch();
}
Output:

3
//Using 2- dimensional array
Source code:
#include<iostream.h>
#include<conio.h>
int main()
{
int a[20][20],i,j,item,flag=0,n,m;
cout<<"Enter row size of array\n";
cin>>n;
cout<<"Enter column size of array\n";

4
cin>>m;
cout<<"Enter the data in the array\n";
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin>>a[i][j];
}
}
cout<<"Enter the element to be searched\n";
cin>>item;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(item==a[i][j])
{
flag=1;
cout<<"Element found at position of list= "<<i<<j;
break;
}
}
}
if(flag==0)
cout<<"Element not found";
getch();
}

5
Output:

1.1.2. Binary search

Binary search is a fast search algorithm with run-time complexity. For this algorithm to work
properly, the data collection should be in the sorted form.

Binary search looks for a particular item by comparing the middle most item of the collection. If
a match occurs, then the index of item is returned. If the middle item is greater than the item,
then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is

6
searched for in the sub-array to the right of the middle item. This process continues on the sub-
array as well until the size of the subarray reduces to zero.

Binary Search Algorithm

1. Start
2. If stop < start then
i. Return -1
3. EndIf
4. mid <- ( start + stop ) / 2
5. If array[ mid ] < search_element then
i. Call BinarySearch( parameters: array, mid + 1, stop, search_element )
6. Else If array[ mid ] > search_element then
i. Call BinarySearch( parameters: array, start, mid - 1, search_element )
7. Else
i. Return mid
8. EndIf
9. Stop

Source code:
//Iterative binary searching using array
#include<iostream.h>
#include<conio.h>
int main()
{
int *list;
int i,item,flag=0,n,mid,left,right,loc=-1;
cout<<"Enter the number of elements to be entered\n";//The maximum size is array size
cin>>n;
list=new int[n];
cout<<"Enter elements in ascending order \n";
for(i=0;i<n;i++)
{
cin>>list[i];
}
cout<<"Enter the element to be searched\n";
cin>>item;

7
left=0;
right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(item==list[mid])
{
loc=mid;
break;
}
else if(list[mid]<item)
left=mid+1;
else
right=mid-1;
}
if(loc==-1)
cout<<"Element not present";
else
cout<<"Element found at= "<<loc;
getch();
}

8
Output:

Source code:
//Recursive binary search using array
#include<iostream.h>
#include<conio.h>
void binary(int [],int,int);
int main()
{
int * list;
int i,item,n;
cout<<"Enter the number of elements to be entered\n";//The maximum size is array size

9
cin>>n;
list= new int[n];
cout<<"Enter elements in ascending order \n";
for(i=0;i<n;i++)
{
cin>>list[i];
}
cout<<"Enter the element to be searched\n";
cin>>item;
binary(list,n,item);
getch();
}
void binary(int list[], int n, int item)
{
int mid,left,right,loc=-1;
left=0;
right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(item==list[mid])
{
loc=mid;
break;
}
else if(list[mid]<item)
left=mid+1;
else
right=mid-1;
}
if(loc==-1)

10
cout<<"Element not present";
else
cout<<"Element found at= "<<loc;
getch();
}
Output:

1.2. Sort algorithm


A Sorting Algorithm is used to rearrange a given array or list elements according to a
comparison operator on the elements. The comparison operator is used to decide the new order
of element in the respective data structure.

1.2.1 Insertion sort


In Insertion sort, iterates the input elements by growing the sorted array at each iteration. It
compares the current element with the largest value in the sorted array. If the current element is
greater, then it leaves the element in its place and moves on to the next element else it finds its
correct position in the sorted array and moves it to that position. This is done by shifting all the
elements, which are larger than the current element, in the sorted array to one position ahead

To sort the array using insertion sort below is the algorithm of insertion sort.
 Spilt a list in two parts - sorted and unsorted.
 Iterate from arr[1] to arr[n] over the given array.

11
 Compare the current element to the next element.
 If the current element is smaller than the next element, compare to the element before,
Move to the greater elements one position up to make space for the swapped element.
Source code:
#include<iostream.h>
#include<conio.h>
void insert(int[],int);
int main()
{
int a[100],i,n;

cout<<"Enter the number of items in the array\n";


cin>>n;
cout<<"Enter the data in the array\n";
for(i=0;i<n;i++)
{
cin>>a[i];

}
insert(a,n);
getch();
}
void insert(int a[], int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i-1;j>=0;j--)
{
if(a[j]>temp)

12
{
a[j+1]=a[j];
}
else
break;
}
a[j+1]=temp;
}
cout<<"Data After Insertion Sort";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}
Output:

1.2.1. Selection sort

The smallest element is selected from the unsorted array and swapped with the leftmost element,
and that element becomes a part of the sorted array. This process continues moving unsorted
array boundary by one element to the right.
Selection sort Algorithm
1. Input n numbers of an array A 2. Initialize i = 0 and repeat through step5 if (i < n – 1)

13
(a) min = a[i]
(b) loc = i
3. Initialize j = i + 1 and repeat through step 4 if (j < n – 1)
4. if (a[j] < min)
(a) min = a[j]
(b) loc = j
5. if (loc ! = i)
(a) swap = a[i]
(b) a[i] = a[loc]
(c) a[loc] = swap
6. Display “the sorted numbers of array A”
7. Exit
Source code:
#include<iostream.h>
#include<conio.h>
int select(int[],int);
int min(int [], int,int);
int main()
{
int a[100],i,n;
cout<<"Enter the number of items in the array\n";
cin>>n;
cout<<"Enter the data in the array\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
select(a,n);
getch();
}
int select(int a[], int n)

14
{
int i,loc,temp;
loc=0;
temp=0;
for(i=0;i<n;i++)
{
loc=min(a,i,n);
temp=a[loc];
a[loc]=a[i];
a[i]=temp;
}
cout<<"Data After Selection Sort\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}
int min(int a[],int lb,int ub)
{
int m=lb;
while(lb<ub)
{
if(a[lb]<a[m])
{
m=lb;
}
lb++;
}
return m;
}
Output:

15
1.2.2. Bubble sort
Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if they
are not in the intended order. The order can be ascending or descending.
ALGORITHM
Let A be a linear array of n numbers. Swap is a temporary variable for swapping (or interchange)
the position of the numbers.
1. Input n numbers of an array A
2. Initialize i = 0 and repeat through step 4 if (i < n)
3. Initialize j = 0 and repeat through step 4 if (j < n – i – 1)
4. If (A[j] > A[j + 1])
(a) Swap = A[j]
(b) A[j] = A[j + 1]
(c) A[j + 1] = Swap
5. Display the sorted numbers of array
A 6. Exit
Source code:
#include<iostream.h>
#include<conio.h>
int bubble(int[],int);
int main()
{

16
int a[100],i,n;
cout<<"Enter the number of items in the array\n";
cin>>n;
cout<<"Enter the data in the array\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
bubble(a,n);
getch();
}
int bubble(int a[], int n)
{
int i,j,p,temp;
for(i=1;i<n;i++)
{
for(p=0;p<n-1;p++)
{
if(a[p]>a[p+1])
{
temp=a[p];
a[p]=a[p+1];
a[p+1]=temp;
}
}
}
cout<<"Data After Bubble Sort\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
}
Output:

17
18
UNIT TWO

Linked lists

2. Creating Linked Lists


Linked List is a linear data structure and it is very common data structure which consists of
group of nodes in a sequence which is divided in two parts. Each node consists of its own data
and the address of the next node and forms a chain. Linked Lists are used to create trees and
graphs.

1. They are a dynamic in nature which allocates the memory when required.
2. Insertion and deletion operations can be easily implemented.
3. Stacks and queues can be easily executed.
4. Linked List reduces the access time.
5. Linked lists are used to implement stacks, queues, graphs, etc.
6. Linked lists let you insert elements at the beginning and end of the list.
7. In Linked Lists we don’t need to know the size in advance.

2.1. Singly Linked List


Singly linked lists contain nodes which have a data part as well as an address part i.e. next,
which points to the next node in sequence of nodes. The operations we can perform on singly
linked lists are insertion, deletion and traversal.

2.1.1. How it works


 Create a node using structure
 Dynamically allocate memory to node
 Create and add nodes to linked list

19
Structure definition
Before creating linked list structure, knowing define structure using struct keyword:

For example:

struct node
{
int data;
struct node *next;
}*start=NULL;
Adding node at beginning
Algorithm:
Insert at front()
{
Allocate a memory for new node(head)
if (head== NULL) then display memory is full (insertion is not possible)
end if
else
read element ele;
head->data=ele;/*copy the data into new1 node */
head->next=header->next;
header->next=head;
end else
}
Example
A linked list is shown below 2->4->6->8->10. If we want to add a new node 1, as the first node
of the list, then the head pointing to node 2 will now point to 1 and the next pointer of node 1
will have a memory address of node 2 as shown in the below figure.

20
Adding node at the ending
Algorithm
Insert at End()
{
Allocate a memory for new node(temp1)
if(temp1== NULL) then display memory is full (insertion is not possible)
end if
else ptr=header
while(ptr->next!=NULL )/*ptr moves end of list */
then ptr=ptr->next
end if
temp1->next=NULL
temp1->data=ele
ptr->next=temp1
end else
}
Example
In the third case, we add a new node at the end of the linked list. Consider we have the same
linked list a->b->c->d->e and we need to add a node f to the end of the list. The linked list will
look as shown below after adding the node.

21
Adding node at given node
Algorithm:
Insert at middle ()
{
Allocate a memory for new node(new1) if (new1== NULL) then
display memory is full (insertion is not possible)
exit
else read ele,pos ptr=header count=0
while(ptr->next!=NULL)
{
ptr=ptr->next;
count ++;
}
if(count<pos-1)
then display position is not of range
end ptr=header count=0
while(count<pos-1)
then ptr=ptr->next
count++ end
new1->data=ele
new1->next=ptr->next
ptr->next=new1 end
else }

22
Example
Here, a node is given and we have to add a new node after the given node. In the below-linked
list a->b->c->d ->e, if we want to add a node f after node c then the linked list will look as
follows:

Source code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/* Node Declaration */
struct node {
int data;
struct node *next;
}*start;
/* Class Declaration */
class single_list {
public:
node* create_node(int);
void insert_begininging();
void insert_position();
void insert_last();
void delete_position();
void sort();

23
void search();
void update();
void reverse();
void display();
single_list()
{
start = NULL;
} };
/* Main :contains menu */
int main()
{
int choice, nodes, element, position, i;
single_list sl;
start = NULL;
while (true)
{
cout<<endl<<"---------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------"<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl;
cout<<"3.Insert node at position"<<endl;
cout<<"4.Sort Link List"<<endl;
cout<<"5.Delete a Particular Node"<<endl;
cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl;
cout<<"8.Display Linked List"<<endl;
cout<<"9.Reverse Linked List "<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;

24
switch(choice)
{
case 1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begininging();
cout<<endl;
break;
case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last();
cout<<endl;
break;
case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_position();
cout<<endl;
break;
case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
cout<<endl;
break;
case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_position();
break;
case 6:
cout<<"Update Node Value:"<<endl;
sl.update();
cout<<endl;
break;

25
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search();
cout<<endl;
break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display();
cout<<endl;
break;
case 9:
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl;
break;
case 10:
cout<<"Exiting..."<<endl;
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
} } } /* * Creating Node */
node *single_list::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node); \
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}

26
else
{
temp->data = value;
temp->next = NULL;
return temp;
} } /* * Inserting element in beginning */
void single_list::insert_begininging()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
p = start;
start = temp;
start->next = p;
}
cout<<"Element Inserted at beginning"<<endl;
} /* * Inserting Node at last */
void single_list::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *s;
temp = create_node(value);

27
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
} /* * Insertion of node at a given position */
void single_list::insert_position()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;

28
}
else
{
ptr = start;
start = temp;
start->next = ptr;
} }
else if (pos > 1 && pos <= counter)
{
s = start;
for (i = 1; i < pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
} } /* * Sorting Link List */
void single_list::sort()
{
struct node *ptr, *s;
int value;
if (start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}

29
ptr = start;
while (ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->data > s->data)
{
value = ptr->data;
ptr->data = s->data;
s->data = value;
} }
ptr = ptr->next;
} } /* * Delete element at a given position */
void single_list::delete_position()
{
int pos, i, counter = 0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{

30
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
} } /* * Update a given Node */
void single_list::update()
{
int value, pos, i;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";

31
cin>>pos; cout<<"Enter the new value: ";
cin>>value;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start->data = value;
}
else
{
for (i = 0;i < pos - 1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return;
}
s = s->next;
}
s->data = value;
}
cout<<"Node Updated"<<endl;
} /* * Searching an element */
void single_list::search()
{
int value, pos = 0;
bool flag = false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;

32
}
cout<<"Enter the value to be searched: ";
cin>>value;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->data == value)
{
flag = true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
}
s = s->next;
}
if (!flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
} /* * Reverse Link List */
void single_list::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{
return;
}
ptr1 = start;

33
ptr2 = ptr1->next;
ptr3 = ptr2->next;
ptr1->next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)
{
ptr1 = ptr2;
ptr2 = ptr3;
ptr3 = ptr3->next;
ptr2->next = ptr1;
}
start = ptr2;
} /* * Display Elements of a link list*/
void single_list::display()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->data<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}

34
2.2. Double linked list
In a doubly linked list, each node contains two links the first link points to the previous node and
the next link points to the next node in the sequence.

2.2.1. How it works


 Create a node using structure
 Dynamically allocate memory to node
 Create and add nodes to linked list
Adding node at the beginning
Algorithm:
Insert at front()
{
Allocate a memory for new node(new1)
if (new1== NULL)
then display memory is full (insertion is not possible)
end if
else
read element ele;
new1->data=ele;/*copy the data into new1 node */
new1->next=header->next;
header->next->prev=new1;
header->next=new1;
new1->prev=header;
end else }
Example
Insertion of a new node at the front of the list. As seen, the previous new node N is set to null.
Head points to the new node. The next pointer of N now points to N1 and previous of N1 that
was earlier pointing to Null now points to N.

35
Adding Node at the end
Algorithm:
Insert at End()
{
Allocate a memory for new node(new1)
if(new1== NULL)
then display memory is full (insertion is not possible)
end if
else
ptr=header
while(ptr->next!=NULL )/*ptr moves end of list */
then ptr=ptr->next
end
new1->next=NULL
new1->prev=ptr;
new1->data=ele
ptr->next=new1
end else }

36
Example
Inserting node at the end of the doubly linked list is achieved by pointing the next pointer of new
node N to null. The previous pointer of N is pointed to N5. The ‘Next’ pointer of N5 is pointed
to N.

Adding node at given position

Algorithm:

Insert at middle () {

Allocate a memory for new node(new1)


if (new1== NULL)
then display memory is full (insertion is not possible)
exit
else
read ele,pos ptr=header count=0
while(ptr->next!=NULL) {
ptr=ptr->next; count ++;
}
if(count<pos-1)
then display position is not of range

37
end
ptr=header count=0
while(count<pos-1)
then ptr=ptr->next
count++
end
new1->data=ele;
new1->next=ptr->next;
new1->prev=ptr;
ptr->next->prev=new1;
ptr->next=new1
end else
}
Example
As shown in the diagram, when we have to add a node before N3 or after N2, we change the
previous and next pointers of the before and after nodes so as to appropriately point to the new
node. Also, the new node pointers are appropriately pointed to the existing nodes.

Source code:
/* C++ Program to Implement Doubly Linked List */
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

38
struct node
{
int data;
struct node *next;
struct node *prev;
}*start=NULL;
void create_list(int);
void add_begining(int);
void add_after(int, int);
void delete_element(int);
void search_element(int);
void display_list();
void count();
void reverse();
/* Main: Contains Menu */
int main()
{
int choice, element, position;
while (true)
{
cout<<endl<<"----------------------------"<<endl;
cout<<endl<<"Operations on Doubly linked list"<<endl;
cout<<endl<<"----------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at begining"<<endl;
cout<<"3.Add after position"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Count"<<endl;
cout<<"7.Reverse"<<endl;
cout<<"8.Quit"<<endl;

39
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the element: ";
cin>>element;
create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
add_begining(element);
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
cout<<"Insert Element after postion: ";
cin>>position;
add_after(element, position);
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"List empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";

40
cin>>element;
delete_element(element);
cout<<endl;
break;
case 5:
display_list();
cout<<endl;
break;
case 6:
count();
break;
case 7:
if (start == NULL)
{
cout<<"List empty, nothing to reverse"<<endl;
break;
}
reverse();
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
} /* Create Double Link List */
void create_list(int value)
{
struct node *s, *temp;

41
temp = new(struct node);
temp->data = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
} } /* Insertion at the beginning */
void add_begining(int value)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->data = value;
temp->next = start;
start->prev = temp;
start = temp;
cout<<"Element Inserted"<<endl;

42
} /* * Insertion of element at a particular position */
void add_after(int value, int pos)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->data = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;
}
else
{

43
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
}
cout<<"Element Inserted"<<endl;
} /* Deletion of element from the list */
void delete_element(int value)
{
struct node *tmp, *q; /*first element deletion*/
if (start->data == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{ /*Element deleted in between*/
if (q->next->data == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}

44
q = q->next;
} /*last element deleted*/
if (q->next->data == value)
{
tmp = q->next;
free(tmp);
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}
/* Display elements of Doubly Link List */
void display_list()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty, nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
cout<<q->data<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
} /* * Number of elements in Doubly Link List */
void count()

45
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q = q->next;
cnt++;
}
cout<<"Number of elements are: "<<cnt<<endl;
} /* Reverse Doubly Link List */
void reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}

46
Output:

47
48
49
2.3. Circular Single Linked List:

In the circular linked list the last node of the list contains the address of the first node and forms
a circular chain. A circular linked list is a variation of the linked list. It is a linked list whose
nodes are connected in such a way that it forms a circle.

In the circular linked list, the next pointer of the last node is not set to null but it contains the
address of the first node thus forming a circle.

Insertion

We can insert a node in a circular linked list either as a first node (empty list), in the beginning,
in the end, or in between the other nodes. Let us see each of these insertion operations using a
pictorial representation below.

#1) Insert in an empty list

50
#2) Insert at the beginning of the list

As shown in the above representation, when we add a node at the beginning of the list, the next
pointer of the last node points to the new node N thereby making it a first node.

N->next = last->next
Last->next = N
#3) Insert at the end of the list

51
To insert a new node at the end of the list, we follow these steps:
N-> next = last ->next;
last ->next = N
last = N

#4) Insert in between the list

Suppose we need to insert a new node N between N3 and N4, we first need to traverse the list
and locate the node after which the new node is to be inserted, in this case, its N3.

After the node is located, we perform the following steps.

52
N -> next = N3 -> next;
N3 -> next = N
This inserts a new node N after N3.

Deletion
The deletion operation of the circular linked list involves locating the node that is to be deleted
and then freeing its memory.

For this we maintain two additional pointers curr and prev and then traverse the list to locate the
node. The given node to be deleted can be the first node, the last node or the node in between.
Depending on the location we set the curr and prev pointers and then delete the curr node.

A pictorial representation of the deletion operation is shown below.

Source code:
/*
* C++ Program to Implement Circular Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
/*
* Node Declaration

53
*/
struct node
{
int info;
struct node *next;
}*last;

/*
* Class Declaration
*/
class circular_llist
{
public:
void create_node(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element(int value);
void search_element(int value);
void display_list();
void update();
void sort();
circular_llist()
{
last = NULL;
}
};

/*
* Main :contains menu
*/
int main()

54
{
int choice, element, position;
circular_llist cl;
while (1)
{
cout<<endl<<"---------------------------"<<endl;
cout<<endl<<"Circular singly linked list"<<endl;
cout<<endl<<"---------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at beginning"<<endl;
cout<<"3.Add after"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Search"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Update"<<endl;
cout<<"8.Sort"<<endl;
cout<<"9.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the element: ";
cin>>element;
cl.create_node(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
cl.add_begin(element);

55
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
cout<<"Insert element after position: ";
cin>>position;
cl.add_after(element, position);
cout<<endl;
break;
case 4:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
cl.delete_element(element);
cout<<endl;
break;
case 5:
if (last == NULL)
{
cout<<"List Empty!! Can't search"<<endl;
break;
}
cout<<"Enter the element to be searched: ";
cin>>element;
cl.search_element(element);
cout<<endl;

56
break;
case 6:
cl.display_list();
break;
case 7:
cl.update();
break;
case 8:
cl.sort();
break;
case 9:
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}

/*
* Create Circular Link List
*/
void circular_llist::create_node(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;

57
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}

/*
* Insertion of element at beginning
*/
void circular_llist::add_begin(int value)
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->info = value;
temp->next = last->next;
last->next = temp;
}

/*
* Insertion of element at a particular place
*/
void circular_llist::add_after(int value, int pos)

58
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp, *s;
s = last->next;
for (int i = 0;i < pos-1;i++)
{
s = s->next;
if (s == last->next)
{
cout<<"There are less than ";
cout<<pos<<" in the list"<<endl;
return;
}
}
temp = new(struct node);
temp->next = s->next;
temp->info = value;
s->next = temp;
/*Element inserted at the end*/
if (s == last)
{
last=temp;
}
}

/*
* Deletion of element from the list

59
*/
void circular_llist::delete_element(int value)
{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;

60
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}

/*
* Search element in the list
*/
void circular_llist::search_element(int value)
{
struct node *s;
int counter = 0;
s = last->next;
while (s != last)
{
counter++;
if (s->info == value)
{
cout<<"Element "<<value;
cout<<" found at position "<<counter<<endl;
return;

61
}
s = s->next;
}
if (s->info == value)
{
counter++;
cout<<"Element "<<value;
cout<<" found at position "<<counter<<endl;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}

/*
* Display Circular Link List
*/
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}

62
cout<<s->info<<endl;
}

/*
* Update Circular Link List
*/
void circular_llist::update()
{
int value, pos, i;
if (last == NULL)
{
cout<<"List is empty, nothing to update"<<endl;
return;
}
cout<<"Enter the node position to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s;
s = last->next;
for (i = 0;i < pos - 1;i++)
{
if (s == last)
{
cout<<"There are less than "<<pos<<" elements.";
cout<<endl;
return;
}
s = s->next;
}
s->info = value;

63
cout<<"Node Updated"<<endl;
}

/*
* Sort Circular Link List
*/
void circular_llist::sort()
{
struct node *s, *ptr;
int temp;
if (last == NULL)
{
cout<<"List is empty, nothing to sort"<<endl;
return;
}
s = last->next;
while (s != last)
{
ptr = s->next;
while (ptr != last->next)
{
if (ptr != last->next)
{
if (s->info > ptr->info)
{
temp = s->info;
s->info = ptr->info;
ptr->info = temp;
}
}
else

64
{
break;
}
ptr = ptr->next;
}
s = s->next;
}
}

65
Output:

66
67
68
2.4. Circular Double Linked List

Circular Doubly Linked List has properties of both doubly linked list and circular linked list in
which two consecutive elements are linked or connected by previous and next pointer and the
last node points to first node by next pointer and also the first node points to last node by
previous pointer.
// Structure of the node

struct node

int info;

struct node *next; // Pointer to next node

struct node *prev; // Pointer to previous node

};

Source code:
/*
* C++ Program to Implement Circular Doubly Linked List
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

/*
* Node Declaration
*/
struct node
{
int info;

69
struct node *next;
struct node *prev;
}*start, *last;
int counter = 0;
/*
* Class Declaration
*/
class double_clist
{
public:
node *create_node(int);
void insert_begin();
void insert_last();
void insert_pos();
void delete_pos();
void search();
void update();
void display();
void reverse();
void sort();
double_clist()
{
start = NULL;
last = NULL;
}
};

/*
* Main: Contains Menu
*/
int main()

70
{
int choice;
double_clist cdl;
while (1)
{
cout<<"\n-------------------------------"<<endl;
cout<<"Operations on Doubly Circular linked list"<<endl;
cout<<"\n-------------------------------"<<endl;
cout<<"1.Insert at Beginning"<<endl;
cout<<"2.Insert at Last"<<endl;
cout<<"3.Insert at Position"<<endl;
cout<<"4.Delete at Position"<<endl;
cout<<"5.Update Node"<<endl;
cout<<"6.Search Element"<<endl;
cout<<"7.Sort"<<endl;
cout<<"8.Display List"<<endl;
cout<<"9.Reverse List"<<endl;
cout<<"10.Exit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cdl.insert_begin();
break;
case 2:
cdl.insert_last();
break;
case 3:
cdl.insert_pos();
break;

71
case 4:
cdl.delete_pos();
break;
case 5:
cdl.update();
break;
case 6:
cdl.search();
break;
case 7:
cdl.sort();
break;
case 8:
cdl.display();
break;
case 9:
cdl.reverse();
break;
case 10:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}

/*
*MEMORY ALLOCATED FOR NODE DYNAMICALLY
*/
node* double_clist::create_node(int value)

72
{
counter++;
struct node *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
temp->prev = NULL;
return temp;
}
/*
*INSERTS ELEMENT AT BEGINNING
*/
void double_clist::insert_begin()
{
int value;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
struct node *temp;
temp = create_node(value);
if (start == last && start == NULL)
{
cout<<"Element inserted in empty list"<<endl;
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
temp->next = start;
start->prev = temp;
start = temp;

73
start->prev = last;
last->next = start;
cout<<"Element inserted"<<endl;
}
}

/*
*INSERTS ELEMNET AT LAST
*/
void double_clist::insert_last()
{
int value;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
struct node *temp;
temp = create_node(value);
if (start == last && start == NULL)
{
cout<<"Element inserted in empty list"<<endl;
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
last->next = temp;
temp->prev = last;
last = temp;
start->prev = last;
last->next = start;
}

74
}
/*
*INSERTS ELEMENT AT POSITION
*/
void double_clist::insert_pos()
{
int value, pos, i;
cout<<endl<<"Enter the element to be inserted: ";
cin>>value;
cout<<endl<<"Enter the postion of element inserted: ";
cin>>pos;
struct node *temp, *s, *ptr;
temp = create_node(value);
if (start == last && start == NULL)
{
if (pos == 1)
{
start = last = temp;
start->next = last->next = NULL;
start->prev = last->prev = NULL;
}
else
{
cout<<"Position out of range"<<endl;
counter--;
return;
}
}
else
{
if (counter < pos)

75
{
cout<<"Position out of range"<<endl;
counter--;
return;
}
s = start;
for (i = 1;i <= counter;i++)
{
ptr = s;
s = s->next;
if (i == pos - 1)
{
ptr->next = temp;
temp->prev = ptr;
temp->next = s;
s->prev = temp;
cout<<"Element inserted"<<endl;
break;
}
}
}
}
/*
* Delete Node at Particular Position
*/
void double_clist::delete_pos()
{
int pos, i;
node *ptr, *s;
if (start == last && start == NULL)
{

76
cout<<"List is empty, nothing to delete"<<endl;
return;
}
cout<<endl<<"Enter the postion of element to be deleted: ";
cin>>pos;
if (counter < pos)
{
cout<<"Position out of range"<<endl;
return;
}
s = start;
if(pos == 1)
{
counter--;
last->next = s->next;
s->next->prev = last;
start = s->next;
free(s);
cout<<"Element Deleted"<<endl;
return;
}
for (i = 0;i < pos - 1;i++ )
{
s = s->next;
ptr = s->prev;
}
ptr->next = s->next;
s->next->prev = ptr;
if (pos == counter)
{
last = ptr;

77
}
counter--;
free(s);
cout<<"Element Deleted"<<endl;
}
/*
* Update value of a particular node
*/
void double_clist::update()
{
int value, i, pos;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to update"<<endl;
return;
}
cout<<endl<<"Enter the postion of node to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s;
if (counter < pos)
{
cout<<"Position out of range"<<endl;
return;
}
s = start;
if (pos == 1)
{
s->info = value;
cout<<"Node Updated"<<endl;

78
return;
}
for (i=0;i < pos - 1;i++)
{
s = s->next;
}
s->info = value;
cout<<"Node Updated"<<endl;
}
/*
* Search Element in the list
*/
void double_clist::search()
{
int pos = 0, value, i;
bool flag = false;
struct node *s;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to search"<<endl;
return;
}
cout<<endl<<"Enter the value to be searched: ";
cin>>value;
s = start;
for (i = 0;i < counter;i++)
{
pos++;
if (s->info == value)
{
cout<<"Element "<<value<<" found at position: "<<pos<<endl;

79
flag = true;
}
s = s->next;
}
if (!flag)
cout<<"Element not found in the list"<<endl;
}
/*
* Sorting Doubly Circular Link List
*/
void double_clist::sort()
{
struct node *temp, *s;
int value, i;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to sort"<<endl;
return;
}
s = start;
for (i = 0;i < counter;i++)
{
temp = s->next;
while (temp != start)
{
if (s->info > temp->info)
{
value = s->info;
s->info = temp->info;
temp->info = value;
}

80
temp = temp->next;
}
s = s->next;
}
}
/*
* Display Elements of the List
*/
void double_clist::display()
{
int i;
struct node *s;
if (start == last && start == NULL)
{
cout<<"The List is empty, nothing to display"<<endl;
return;
}
s = start;
for (i = 0;i < counter-1;i++)
{
cout<<s->info<<"<->";
s = s->next;
}
cout<<s->info<<endl;
}
/*
* Reverse Doubly Circular Linked List
*/
void double_clist::reverse()
{
if (start == last && start == NULL)

81
{
cout<<"The List is empty, nothing to reverse"<<endl;
return;
}
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != start)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
last = start;
start = p1;
cout<<"List Reversed"<<endl;
}

82
Output:

83
84
85
UNIT THREE

Stack

3. Stack Implementation
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

Mainly the following three basic operations are performed in the stack:

Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in the reversed order in which
they are pushed. If the stack is empty, then it is said to be an Underflow condition.

3.1. Array implementation of stack


3.1.1. Pop operation
Algorithm:
Step 1: If the Stack is empty then give the alert "Stack underflow" and quit; or else go to step-2
Step 2: a) Hold the value for the element pointed by the TOP
            b) Put a NULL value instead
            c) Decrement the TOP by 1
3.1.2. Push operation

Algorithm:

Step-1: Increment the Stack TOP by 1.

Check whether it is always less than the Upper Limit of the stack.

If it is less than the Upper Limit go to step-2

Else

86
Report -"Stack Overflow"
Step-2: Put the new element at the position pointed by the TOP.

Example:

The above example shows the sequence of operations that are performed on the stack. Initially,
the stack is empty. For an empty stack, the top of the stack is set to -1.
Next, we push the element 10 into the stack. We see that the top of the stack now points to
element 10.
Next, we perform another push operation with element 20, as a result of which the top of the
stack now points to 20. This state is the third figure.

87
Now in the last figure, we perform a pop () operation. As a result of the pop operation, the
element pointed at the top of the stack is removed from the stack. Hence in the figure, we see
that element 20 is removed from the stack. Thus the top of the stack now points to 10.

Source code:
#include<iostream.h>
#include<conio.h>
#define MAXSIZE 10
void push();
int pop();
void traverse();
int stack[MAXSIZE];
int Top=-1;
int main()
{
int choice; char ch;
do
{
cout<<"1: Push element\n ";
cout<<"2: Pop data item\n";
cout<<"3; Traverse items \n";
cout<<"\nEnter your choice";
cin>>choice;
switch(choice)
{
case 1: push();
break;
case 2:
cout<<"\nThe deleted element is"<<pop();
break;
case 3:

88
traverse();
break;
default:
cout<<"\nYou Entered Wrong Choice";
}
cout<<"\nDo You Wish To Continue (Y/N)";
cin>>ch;
}
while(ch=='Y' || ch=='y');
}
void push()
{
int item;
if(Top == MAXSIZE - 1)
{
cout<<"\nThe Stack Is Full";
getch();
exit(0);
}
else
{
cout<<"Enter the element to be inserted";
cin>>item;
Top= Top+1;
stack[Top] = item;
}
}
int pop()
{
int item;
if(Top == -1)

89
{
cout<<"The stack is Empty";
getch();
exit(0);
}
else
{
item = stack[Top];
Top = Top-1;
}
return(item);

void traverse()
{
int i;
if(Top == -1)
{
cout<<"The Stack is Empty";
getch();
exit(0);
}
else
{
for(i=Top;i>=0;i--)
{
cout<<"Traverse the element";
cout<<stack[i];
}
}}

90
Output:

91
3.2. Stack as linked list
3.2.1. Push operation:

Algorihm:
1. Create new node temp
2. Enter data to be inserted
3. Read inserted data n
4. Temp->data=n;
5. Temp->next = top
6. Top = temp
7. Return
3.2.2. Pop operation:

Algorihm:
1. If (top = NULL)
Print “ underflow”
Return
2. x = top
3. top = top ->next
4. delete node(x)
5. Return
Source code:
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* top = NULL;
void push(int val) {

92
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}
void pop() {
if(top==NULL)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< top->data <<endl;
top = top->next;
}
}
void display() {
struct Node* ptr;
if(top==NULL)
cout<<"stack is empty";
else {
ptr = top;
cout<<"Stack elements are: ";
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;

93
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

94
Output:

3.3. Algorithm to convert an infix to postfix expression


Algorithm:
Q is arithmetic expression
P is postfix expression
1. Push “(“ onto stack, and add “)” to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each

95
element of Q until the stack is empty
3. If an operand is encountered , add it to P
4. If a left parenthesis is encountered, push it onto stack
5. If an operator is encountered , then:
(a) Repeatedly pop from stack and add to P each operator
which has the same precedence as or higher precedence
than
(b) Add to stack
6. If a right parenthesis is encountered, then:
(a) Repeatedly pop from stack and add to P each operator until
a left parenthesis is encountered
(b) Remove the left parenthesis
7. Exit
Source code:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<iostream.h>
int F(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
case '$':
return 5;

96
case '(':
return 0;
case '#':
return -1;
default:
return 8;
}}
int G(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 3;
case '^':
case '$':
return 6;
case '(':
return 9;

case ')':
return 0;

default: return 7;
}
}
void infix_postfix(char infix[], char postfix[])
{

97
int top, j, i;
char s[30], symbol;
top = -1;
s[++top] = '#';
j = 0;
for(i=0; i < strlen(infix); i++)
{
symbol = infix[i];
while(F(s[top]) > G(symbol))
{
postfix[j] = s[top--];
j++;
}
if(F(s[top]) != G(symbol))
s[++top] = symbol;
else
top--;
}
while(s[top] != '#')
{
postfix[j++] = s[top--];
}
postfix[j] = '\0';
}

int main()
{
char infix[100], postfix[100];
cout<<"\nEnter a valid infix expression\n";
cin>>infix;
infix_postfix(infix,postfix);

98
cout<<"\nThe infix expression is:\n";
cout<<infix;
cout<<"\nThe postfix expression is:\n";
cout<<postfix;
getch();
}
Output:

99
UNIT FOUR

Queue

4. Queue implementations
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at
both its ends. One end is always used to insert data (enqueue) and the other is used to remove
data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will
be accessed first.

4.1. Array implementation of enqueue and dequeue operation


Analysis:
Consider the following structure:
int Num[MAX_SIZE];
int FRONT =-1,REAR =-1;
int QUEUESIZE=0;
 To enqueue data to the queue
o check if there is space in the queue
REAR<MAX_SIZE-1 ?
Yes: - Increment REAR
- Store the data in Num[REAR]
- Increment QUEUESIZE
FRONT = = -1?
Yes: - Increment FRONT
No: - Queue Overflow
 To dequeue data from the queue
o check if there is data in the queue
QUEUESIZE > 0 ?
Yes: - Copy the data in Num[FRONT]
- Increment FRONT
- Decrement QUEUESIZE

100
No: - Queue Underflow
Source code:
#include <iostream>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else {
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow ";
return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}
void Display() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {

101
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
cout<<endl;
}
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}

102
Output:

103
4.2. Circular array implementation of enqueue and dequeue

Consider the following analysis structure:


int Num[MAX_SIZE];
int FRONT =-1,REAR =-1;
int QUEUESIZE=0;
To enqueue data to the queue
o check if there is space in the queue
QUEUESIZE<MAX_SIZE ?
Yes: - Increment REAR
REAR = = MAX_SIZE ?
Yes: REAR = 0
- Store the data in Num[REAR]
- Increment QUEUESIZE
FRONT = = -1?
Yes: - Increment FRONT
No: - Queue Overflow
To dequeue data from the queue
o check if there is data in the queue
QUEUESIZE > 0 ?
Yes: - Copy the data in Num[FRONT]
- Increment FRONT
FRONT = = MAX_SIZE ?
Yes: FRONT = 0
- Decrement QUEUESIZE
No: - Queue Underflow
Source code:
#include <iostream>
using namespace std;
int cqueue[50];
int front = -1, rear = -1, n=5;

104
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;

if (front == rear) {
front = -1;
rear = -1;
} else {
if (front == n - 1)
front = 0;
else
front = front + 1;

105
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {

int ch, val;


cout<<"1)Insert\n";

106
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}

107
Output:

108
4.3. Double ended queue using linked list
Algorithm:
insert_begin(x) {
Allocate a memory for new node(new1) new1 -> data =x;
new1 ->previous = new1 ->next =NULL;
if(front == NULL||rear==NULL)
front = rear = new1;
else {
new1 ->next = front;
front ->previous = new1;
front = new1;
} }
Algorithm: insert_last(x) {
Allocate a memory for new node (new1) new1 ->data = x;
new1 -> previous = new1 ->next = NULL;
if (front == NULL||rear==NULL) front = rear = new1;
else {
rear ->next = new1; new1 ->previous = rear; rear = new1;
} }
Algorithm: delete_begin() {
if (front == NULL || rear==NULL)
{
Display List is empty }
else {
temp = front; /*assign the temp point at front node*/ x= temp->data;
if(front==rear) //verify list having only one node then update the list is empty {
front=NULL; rear=NULL; }
else
{

109
front = front->next; front->previous = NULL;
}
count --; // decrease the no.of nodes in the list delete the temp node
} }
delete_last( ) {
if(rear == NULL || front==NULL)
{
Display List is empty
}
else
{
temp = rear; /*assign the temp point at rear node*/
if(front==rear) //verify list having only one node then update the list is empty
{
front=NULL; rear=NULL;
}
else
{
rear = rear->previous; rear -> next = NULL; }
x= temp ->data;
delete the temp node count --; // decrease the no.of nodes in the list return x;
} }

Source code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:

110
int data;
class node *next;
class node *prev;
};
class dqueue: public node
{
node *head,*tail;
int top1,top2;
public:
dqueue()
{
top1=0;
top2=0;
head=NULL;
tail=NULL;
}
void push(int x)
{
node *temp;
int ch;
if(top1+top2 >=5)
{
cout <<"dqueue overflow";
return ;
}
if( top1+top2 == 0)
{
head = new node;
head->data=x;
head->next=NULL;
head->prev=NULL;

111
tail=head;
top1++;
}
else
{
cout <<" Add element 1.FIRST 2.LAST\n enter ur choice:";
cin >> ch;
if(ch==1)
{
top1++;
temp=new node;
temp->data=x;
temp->next=head;
temp->prev=NULL;
head->prev=temp;
head=temp;
}
else
{
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
}
}
}
void pop()
{

112
int ch;
cout <<"Delete 1.First Node 2.Last Node\n Enter ur choice:";
cin >>ch;
if(top1 + top2 <=0)
{
cout <<"\nDqueue under flow";
return;
}
if(ch==1)
{
head=head->next;
head->prev=NULL;
top1--;
}
else
{
top2--;
tail=tail->prev;
tail->next=NULL;
}
}
void display()
{
int ch;
node *temp;
cout <<"display from 1.Staring 2.Ending\n Enter ur choice";
cin >>ch;
if(top1+top2 <=0)
{
cout <<"under flow";
return ;

113
}
if (ch==1)
{
temp=head;
while(temp!=NULL)
{
cout << temp->data <<" ";
temp=temp->next;
}
}
else
{
temp=tail;
while( temp!=NULL)
{
cout <<temp->data << " ";
temp=temp->prev;
}
}
}
};
int main()
{
dqueue d1;
int ch;
while (true)
{
cout <<"1.INSERT 2.DELETE 3.DISPLAU 4.EXIT\n Enter ur choice:";
cin >>ch;
switch(ch)
{

114
case 1:
cout <<"enter element";
cin >> ch;
d1.push(ch); break;
case 2:
d1.pop();
break;
case 3:
d1.display();
break;
case 4: exit(1);
} }}

115
Output:

116
117
UNIT FIVE

Binary search tree

5. Binary search tree


5.1. Implementation of binary search tree

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −
 The left sub-tree of a node has a key less than or equal to its parent node's key.
 The right sub-tree of a node has a key greater than to its parent node's key.

Algorithm
Insert(root, ele)
{
if tree is empty then insert a node as root node otherwise go to next step
if ele is less than the root node the insert left sub tree of root node
otherwise insert right sub tree of root node
}
Algorithm: inorder(struct node *ptr) {
if(ptr==NULL) return;
else {
Visit inorder(ptr->left)
diplay ptr->data
Visit inorder(ptr->right)
} }
Source code:
//Binary search tree
#include<iostream.h>
struct node
{

118
int data;
node *left;
node *right;
};
node *root = NULL;
void display(node *ptr, int level)
{
int i;
if (ptr != NULL)
{
display(ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<"Root->: ";
else
{
for (i = 0;i < level; i++)
cout<<"\t";
}
cout<<ptr->data;
display(ptr->left, level+1);
}
if(root == NULL)
cout<<"\n The BST is empty ... \n\n";
}
void Create_Insert(node *RNP,int item)
{
node *temp = new node;
temp->data = item;
temp->left = NULL;
temp->right = NULL;

119
node *INP = new node;
INP->data = item;
INP->left = NULL;
INP->right = NULL;
int Inserted = 0;
while(Inserted == 0)
{
if (root == NULL)
{
root = INP;
cout<<"\t Root Node is Added"<<endl;
break;
}
if (RNP->data == INP->data)
{
cout<<"\t Element already in the tree"<<endl;
cout<<"\t Please, enter distinct value for current node :";
cin>>item;
Create_Insert(root, item);
break;
}
if(RNP->data > INP->data)
{
if(RNP->left == NULL)
{
RNP->left = INP;
Inserted = 1;
cout<<"\t Left node is added."<<endl;
}
else
RNP = RNP->left;

120
}
else
{
if(RNP->right == NULL)
{
RNP->right = INP;
Inserted = 1;
cout<<"\t Right node is added."<<endl;
}
else
RNP = RNP->right;
}}}
int main( )
{
int n, value, choice;
while(true)
{
cout<<"\n\n What do you want? \n";
cout<<"\t 1.To Create the BST:\n";
cout<<"\t 2.To Display the BST:\n";
cout<<"\t 3.To Quit the program:\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"How many elements/nodes u have to store in the tree?.";
cin>>n;
for(int i =1; i <= n; i++)
{
cout<<"\t Enter value for node"<<i<<" :";

121
cin>>value;
Create_Insert(root, value);
}
break;
case 2:
cout<<endl<<endl;
display(root, 1);
cout<<endl<<endl;
break;
case 3:
exit(1);
default:
cout<<"Uppp, wrong choice !!!"<<endl;
}}}

122
5.2. Traverse
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, trees can be traversed in different ways
We have already discussed the traversals for the binary tree. In the case of BST as well, we can
traverse the tree to get inOrder, preorder or postOrder sequence. In fact, when we traverse the
BST in Inorder sequence, then we get the sorted sequence.
Algorithm:
Insert(root, ele)
{
if tree is empty then insert a node as root node otherwise go to next step
if ele is less than the root node the insert left sub tree of root node otherwise insert right sub tree
of root node
}
Algorithm :inorder(ptr)
{
Initially top=-1;
if(ptr==NULL)
return;
else {
while(ptr!=NULL||top>=0)
{
if(ptr!=NULL)
{
top++;//push the value in stack
stack[top]=ptr;
ptr=ptr->left;
}
else
{
ptr=stack[top];
display ptr->data top--; //pop the stack

123
ptr=ptr->right; } } } }
Source Code:
#include<iostream>
using namespace std;

// Node class
class Node {
int key;
Node* left;
Node* right;
public:
Node()
{
key=-1;
left=NULL;
right=NULL; };
void setKey(int aKey) { key = aKey; };
void setLeft(Node* aLeft) { left = aLeft; };
void setRight(Node* aRight) { right = aRight; };
int Key() { return key; };
Node* Left() { return left; };
Node* Right() { return right; }; };

// Tree class
class Tree
{
Node* root;
public:
Tree();
~Tree();
Node* Root() { return root; };

124
void addNode(int key);
void inOrder(Node* n);
void preOrder(Node* n);
void postOrder(Node* n); private:
void addNode(int key, Node* leaf);
void freeNode(Node* leaf); };

// Constructor
Tree::Tree()
{
root = NULL;
}

// Destructor
Tree::~Tree()
{
freeNode(root);
}

// Free the node


void Tree::freeNode(Node* leaf)
{
if ( leaf != NULL )
{
freeNode(leaf->Left());
freeNode(leaf->Right());
delete leaf;
}}

// Add a node
void Tree::addNode(int key)

125
{ // No elements. Add the root
if ( root == NULL )
{
cout << "add root node ... " << key << endl;
Node* n = new Node();
n->setKey(key);
root = n;
}
Else
{
cout << "add other node ... " << key << endl;
addNode(key, root);
}}
// Add a node (private)
void Tree::addNode(int key, Node* leaf)
{
if ( key <= leaf->Key() )
{
if ( leaf->Left() != NULL )
addNode(key, leaf->Left());
else
{
Node* n = new Node();
n->setKey(key);
leaf->setLeft(n);
} }
else
{
if ( leaf->Right() != NULL )
addNode(key, leaf->Right());
else

126
{
Node* n = new Node();
n->setKey(key);
leaf->setRight(n);
} }}

// Print the tree in-order // Traverse the left sub-tree, root, right sub-tree
void Tree::inOrder(Node* n)
{
if ( n )
{
inOrder(n->Left());
cout << n->Key() << " ";
inOrder(n->Right());
}}
// Print the tree pre-order // Traverse the root, left sub-tree, right sub-tree
void Tree::preOrder(Node* n)
{
if ( n )
{
cout << n->Key() << " ";
preOrder(n->Left());
preOrder(n->Right());
}}
// Print the tree post-order // Traverse left sub-tree, right sub-tree, root
void Tree::postOrder(Node* n)
{
if ( n )
{
postOrder(n->Left());
postOrder(n->Right());

127
cout << n->Key() << " ";
}}
// Test main program
int main() {
Tree* tree = new Tree();
tree->addNode(30);
tree->addNode(10);
tree->addNode(20);
tree->addNode(40);
tree->addNode(50);
cout << "In order traversal" << endl;
tree->inOrder(tree->Root());
cout << endl; cout << "Pre order traversal" << endl;
tree->preOrder(tree->Root());
cout << endl;
cout << "Post order traversal" << endl;
tree->postOrder(tree->Root());
cout << endl;
delete tree; return 0; }

Output:

128
UNIT SIX

Advanced Sorting and Searching Algorithms


6.1. Quick sort
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into two arrays one of which holds values smaller
than the specified value, say pivot, based on which the partition is made and another array holds
values greater than the pivot value.
Algoritm:
1. low =l, high = h, key a[(l+h)/2]
2. Repeat through step 7 while (low <= high)
3. Repeat step 4 while (a[low] < key)
4. low = low +1
5. Repeat step 6 while (a[high] > key)
6. high = high – 1
7. If (low <= high)
a) temp = a[low]
b) a[low] = a[high]
c) a[high] = temp
d) low = low + 1
e) high = high + 1
8. If (l < high) quicksort (a,l,high)
9. If (h>low) quicksort (a,low,h)
10. Exit
Source code:
#include<conio.h>
#include<iostream.h>
#define max 100

129
int a[max],n,i,l,h;
int main()
{
void input(void);
input();
getch();
}

void input(void)
{
void output(int a[],int n);
void quick_sort(int a[],int l,int h); cout<<"How many elements in the array : ";
cin>>n;
cout<<"\n";
cout<<"Enter the elemennts : \n";
for(i=0;i<=n-1;i++)
{
cin>>a[i];
}
l=0;
h=n-1;
quick_sort(a,l,h);
cout<<"Sorted Array :\n "; output(a,n);
}

void quick_sort(int a[],int l, int h)


{
int temp,key,low,high; low=l;
high=h; key=a[(low+high)/2];
do
{

130
while(key>a[low])
{
low++;
}
while(key<a[high])
{
high--;
}
if(low<=high)
{
temp=a[low];
a[low++]=a[high];
a[high--]=temp;
}
}
while(low<=high);
if(l<high)
quick_sort(a,l,high);
if(low<h)
quick_sort(a,low,h);
}
void output(int a[],int n)
{
for(i=0;i<=n-1;i++)
{
cout<<endl;
cout<<a[i];
}
}

131
Output:

6.2. Heap sort


Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is
similar to selection sort where we first find the maximum element and place the maximum
element at the end. We repeat the same process for remaining element.
Algorithm:
The heap sort algorithm consists of these steps:
1. Build the heap using all elements of the array.
2. Poll the highest element of the heap.
3. Swap it with the last element of the heap (in array).
4. Reduce the heap size by 1 (elements at the end of the heap are already sorted).
5. Repair the heap (move element swapped in 3 to its correct place in the structure).
6. If there are any elements remaining in the heap GOTO: 2.
7. Array is sorted according to the priority of the elements in reverse order.
Source Code:

132
/* C++ Program to Implement Heap Sort */
#include <iostream>
#include <conio.h>
using namespace std;
void max_heapify(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2*i;
while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j+1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j/2] = a[j];
j = 2*j;
}
}
a[j/2] = temp;
return;
}
void heapsort(int *a, int n)
{
int i, temp;
for (i = n; i >= 2; i--)
{
temp = a[i];
a[i] = a[1];

133
a[1] = temp;
max_heapify(a, 1, i - 1);
}}
void build_maxheap(int *a, int n)
{
int i;
for(i = n/2; i >= 1; i--)
{
max_heapify(a, i, n);
}}
int main()
{
int n, i, x;
cout<<"enter no of elements of array\n";
cin>>n;
int a[20];
for (i = 1; i <= n; i++)
{
cout<<"enter element"<<(i)<<endl;
cin>>a[i];
}
build_maxheap(a,n);
heapsort(a, n);
cout<<"sorted output\n";
for (i = 1; i <= n; i++)
{
cout<<a[i]<<endl;
}
getch();
}
Output:

134
6.3. Merge sort
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two
halves, calls itself for the two halves and then merges the two sorted halves.
Objective:
Algorithm for sorting a list of integers in ascending order.
Source Code:
#include<iostream.h>
#include<conio.h>

135
void mergesort(int a[],int,int);
void merge(int[],int,int,int);
int main()
{
int a[20],i,n;
cout<<"Enter the number of elements\n";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
mergesort(a,0,n-1);
cout<<"Data After Merge Sort\n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}
void mergesort(int a[],int lb,int ub)
{
int mid;
if(lb<ub)
{
mid=(lb+ub)/2;
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid+1,ub);
}
}
void merge(int a[], int lb, int mid, int ub)
{

136
int k,p1,p2,p3,b[20];
p1=lb;
p3=lb;
p2=mid;
while((p1<mid)&& (p2<=ub))
{
if(a[p1]<=a[p2])
b[p3++]=a[p1++];
else
b[p3++]=a[p2++];
}
while(p1<mid)
{
b[p3++]=a[p1++];
}
while(p2<=ub)
{
b[p3++]=a[p2++];
}
for(k=lb;k<p3;k++)
{
a[k]=b[k];
}}
Output:

137
Chapter Six
Hash Function

A Hash function is a function that maps any kind of data of arbitrary size to fixed-size values.
The values returned by the function are called Hash Values or digests. There are many popular
Hash Functions such as DJBX33A, MD5, and SHA-256. This post will discuss the key features,
implementation, advantages and drawbacks of the Polynomial Rolling Hash Function.

138

You might also like