0% found this document useful (0 votes)
12 views

Data Structures and Algorithms (Using C++)

Data structure and algorithms using c++notes

Uploaded by

ellen deus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Data Structures and Algorithms (Using C++)

Data structure and algorithms using c++notes

Uploaded by

ellen deus
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

COURSE TITLE: DATA STRUCTURES AND ALGORITHMS

CODE: CS 2201

LECTURER: MR. ARAKA

PURPOSE OF THE COURSE

Students will learn about fundamental computing algorithms, including searching and
sorting; elementary abstract data types including linked lists, stacks, queues and trees; and
elementary algorithm analysis.

EXPECTED LEARNING OUTCOMES

By the end of the course unit, students should be able to:

▪ Explain the basics of Abstract Data Types.

▪ Discuss algorithms and its application to programming data structures

▪ Describe program features (structures) found in typical programming


language

▪ Use OOP for classes to implement data structures using example


programming languages such as Python, C++

COURSE CONTENT

Overview of high level languages

• Time and space analysis of algorithms, Order Notations

Linear Data Structures

• Sequential representations: arrays and lists, stacks, queues and de-queues, strings,
applications; Link representation: Linear linked lists, Circularly linked lists, Doubly
linked lists, applications.

Recursion

• Design of recursive algorithms, Tail Recursion, when not to use recursion, Removal
of recursion.

Non-linear Data Structure

• Trees, Binary Trees, Traversals and Threads, Binary Search Trees, Insertion and
Deletion algorithms, Height-balanced and weight-balanced trees, B-trees, B+ -trees,
Applications of trees

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 1


Graphs

• Representations, Breadth-first and Depth-first Search

Hashing

• Hashing Functions, Collision Resolution Techniques.

Sorting and Searching Algorithms

• Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, Merge Sort, Heap Sort and
Radix Sort.

File Structures

• Sequential and Direct Access; Relative Files; Indexed Files: B+ tree as index; Multi-
indexed Files, Inverted Files, Hashed Files

MODE OF DELIVERY

• Lectures

• Reading assignments

• Practical assignments

• Field trips

• Documentaries

INSTRUCTIONAL MATERIALS AND / OR EQUIPMENT

• Whiteboard and Markers

• Flip Charts

• LCD Projectors

• CDs, DVDs and Tapes

COURSE ASSESSMENT

• Continuous assessments tests 20%

• Group and individual project (course work) 20%

• End of Semester Examination 60%

Total 100%

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 2


READING MATERIALS

1. Hanley, Koffman (1999). Problem Solving & Program Design in C, 3rd ed., Addison-
Wesley, USA

2. Sebesta (1999). Concepts of Programming Languages, 4th ed., Addison-Wesley, USA

3. Savitch (2001). Problem Solving with C++: The Object of Programming, 3 rd ed.,
Addison Wesley Longman Inc., USA

4. Bayer (2002). Visual Basic 6, Addison-Wesley, Great Britain

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 3


INTRODUCTION

Flowchart – is a pictorial representation of an algorithm

Pseudo-code – is an informal is an informal way of writing a program for better human


understanding

Or is a way of expressing an algorithm without conforming to specific syntax rules.

Data structure

A data structure is a specialized format for organizing and storing data. General data
structure types include the array, the file, the record, the table, the tree, and so on.

Any data structure is designed to organize data to suit a specific purpose so that it can be
accessed and worked with in appropriate ways.

Characteristics of a Data Structure

1. Correctness − Data structure implementation should implement its interface correctly.

2.Time Complexity − Running time or the execution time of operations of data structure
must be as small as possible.

3. Space Complexity − Memory usage of a data structure operation should be as little as


possible.

Need for Data Structure

As applications are getting complex and data rich, there are three common problems that
applications face now-a-days.

a) Data Search − Consider an inventory of 1 million-(106) items of a store. If the


application is to search an item, it has to search an item in 1 million-(106) items every
time slowing down the search. As data grows, search will become slower.
b) Processor speed − Processor speed although being very high, falls limited if the data
grows to billion records.
c) Multiple requests − As thousands of users can search data simultaneously on a web
server, even the fast server fails while searching the data. Data can be organized in a

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 4


data structure in such a way that all items may not be required to be searched, and the
required data can be searched almost instantly.

ALGORITHM

Definition : Definition: - An algorithm is a Step By Step process to solve a problem, where


each step indicates an intermediate task. Algorithm contains finite number of steps that leads
to the solution of the problem.

Features/properties/characteristics of algorithms.

Not all procedures can be called an algorithm. An algorithm should have the following
characteristics –

1.Unambiguous −Each of its steps (or phases), and their inputs/outputs should be clear and
must lead to only one meaning.

2.Input − An algorithm should have 0 or more well-defined inputs.

3.Output − An algorithm should have 1 or more well-defined outputs, and should match the
desired output.

4. Finiteness − Algorithms must terminate after a finite number of steps.

5.Feasibility − Should be feasible with the available resources.

6.Independent − An algorithm should have step-by-step directions, which should be


independent of any programming code. It should be efficient both in terms of memory and
time.

Generality: Algorithm is generalized one. It works on all set of inputs and provides the
required output. In other words it is not restricted to a single input value.

Algorithm Development Life Cycle

The life cycles of an algorithm includes the following phases:

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 5


1) Design Phase: Some of the techniques used in the design phase of an algorithm are

(i) Brute-Force Method

(ii) Divide-Conquer Method (

iii) Greedy Method (

iv) Dynamic Programming

(v) Backtracking

2) Writing Phase: Basically algorithm is written in a modular approach. Actually a function


written to solve a particular problem is itself an algorithm. To make clear each and every
step in the algorithm, write comments wherever necessary.

3) Testing Phase: After writing an algorithm, it is necessary to check that the algorithm gives
correct result for every valid input.

4) Analyzing Phase: Suppose for a problem P, ten correct algorithms are designed. Now
which one is to be chosen that depends on the performance of them. Mainly this performance
is judged based on how much time and space the algorithm takes. That is after testing phase
of an algorithm it is required to analyze the time complexity and space complexity of it. In
section 2.5 this is discussed in details.

PROGRAMMING PERFORMANCE/PERFORMANCE ANALYSIS OF AN


ALGORITHM

Performance of a program: The performance of a program is measured based on the


amount of computer memory and time needed to run a program.

The two approaches which are used to measure the performance of the program are:

1. Analytical method à called the Performance Analysis.

2. Experimental method à called the Performance Measurement.

The Efficiency of an Algorithm can be measured by the following metrics.

a)Space Complexity.

b) Time Complexity

a) SPACE COMPLEXITY

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 6


Space complexity: The Space complexity of a program is defined as the amount of memory
it needs to run to completion.

The space complexity can be measured using experimental method, which is done by running
the program and then measuring the actual space occupied by the program during execution.

Space complexity is the sum of the following components.

(i) Instruction space:

The program which is written by the user is the source program. When this program is
compiled, a compiled version of the program is generated. For executing the program an
executable version of the program is generated. The space occupied by these three when the
program is under execution, will account for the instruction space.

(ii) Data space:

The space needed by the constants, simple variables, arrays, structures and other data
structures will account for the data space.

The Data space depends on the following factors:

• Structure size – It is the sum of the size of component variables of the structure.

• Array size – Total size of the array is the product of the size of the data type and the
number of array locations.

(iii) Environment stack space:

The Environment stack space is used for saving information needed to resume execution of
partially completed functions. That is whenever the control of the program is transferred
from one function to another during a function call, then the values of the local variable of
that function and return address are stored in the environment stack. This information is
retrieved when the control comes back to the same function.

The environment stack space depends on the following factors:

• Return address

• Values of all local variables and formal parameters.

b) TIME COMPLEXITY

Time complexity: Time complexity of the program is defined as the amount of computer
time it needs to run to completion

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 7


The time complexity can be measured, by measuring the time taken by the program when it is
executed. This is an experimental method. But this is done very rarely. We always try to
estimate the time consumed by the program even before it is run for the first time.

The time complexity of the program depends on the following factors:

a)Compiler used – some compilers produce optimized code which consumes less time to get
executed. b)Compiler options – The optimization options can be set in the options of the
compiler.

c)Target computer – The speed of the computer or the number of instructions executed per
second differs from one computer to another.

The total time taken for the execution of the program is the sum of the compilation time
and the execution time.

(i) Compile time – The time taken for the compilation of the program to produce the
intermediate object code or the compiler version of the program. The compilation time is
taken only once as it is enough if the program is compiled once. If optimized code is to be
generated, then the compilation time will be higher.

(ii) Run time or Execution time - The time taken for the execution of the program. The
optimized code will take less time to get executed.

Time complexity T(P) = c + T p

c -Compile time

Tp - Run time or execution time

We will be interested in estimating only the execution time as this is the one which varies
according to the user input.

ASYMPTOTIC NOTATIONS

Asymptotic notations are the notations used to describe the behavior of the time or space
complexity.

Let us represent the time complexity and the space complexity using the common function
f(n).

Asymptotic analysis refers to computing the running time of any operation in mathematical
units of computation. For example, the running time of one operation is computed as f(n) and
may be for another operation it is computed as g(n2). This means the first operation running
time will increase linearly with the increase in n and the running time of the second operation
will increase exponentially when n increases. Similarly, the running time of both operations
will be nearly the same if n is significantly small.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 8


The time required by an algorithm falls under three types –

• Best Case − Minimum time required for program execution.


• Average Case − Average time required for program execution.
• Worst Case − Maximum time required for program execution. Asymptotic

The various asymptotic notations are:

(i) O ( Big Oh notation )

(ii) ( Omega notation ) Ω

(iii) ( Theta notation ) θ

(iv) o ( Little Oh notation )

O – Big Oh notation

The big Oh notation provides an upper bound for the function f(n).

The function f(n) = O(g(n)) if and only if there exists positive constants c and n 0 such that
f(n) ≤ cg(n) for all n ≥ n 0.

Examples:

1. f(n) = 3n + 2

Let us take g(n) = n

c = 4

n0 =2

Let us check the above condition

3n + 1 ≤ 4n for all n ≥ 2

The condition is satisfied. Hence f(n) = O(n).

2. f(n) = 10n2 + 4n + 2

Let us take g(n) =n2

c = 11

n0 = 6

Let us check the above condition

10n2 + 4n + 2 ≤ 11n for all n ≥ 6

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 9


The condition is satisfied. Hence f(n) = O(n 2).

- Omega notationΩ

The notation gives the lower bound for the function f(n). Ω

The function f(n) = (g(n)) if and only if there exists positive constants Ω c and n 0 such that
f(n) ≥ cg(n) for all n ≥ n 0.

Examples:

1. f(n) = 3n + 2

Let us take g(n) = n

c = 3

n0 = 0

Let us check the above condition

3n + 1 ≥ 3n for all n ≥ 0

The condition is satisfied. Hence f(n) = (n). Ω

2. f(n) = 10n 2 + 4n + 2

Let us take g(n) = n 2

c = 10 n0 = 0

Let us check the above condition

10n 2 + 4n + 2 10n ≥ for all n 0 ≥

The condition is satisfied. Hence f(n) = (n Ω 2).

– Theta notationθ

The theta notation is used when the function f(n) can be bounded by both from above and
below the same function g(n).

f(n) = (g(n)) if and only if there exists some positive constants c 1 and c2 and n 0, such that
c1g(n) ≤ f(n) c 2g(n) for all n n ≥ 0.

We have seen in the previous two cases,

3n + 2 = O(n) and 3n + 2 = (n) Ω

Hence we can write 3n + 2 = (n) θ

o - Little Oh notation

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 10


f(n) = o(g(n)) if and only if f(n) = O(g(n)) and f(n) (g(n)) ≠ Ω

For example,

3n + 2 = O(n 2) but 3n + 2 (n ≠ Ω 2)

Therefore it can be written as 3n + 2 = o(n 2)

DATA STRUCTURES

Classification of Data structures

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 11


Data structures can be classified into the following categories

a) Primitive data structures


Primitive Data structures are directly supported by the language ie; any operation is
directly performed in these data items. e.g integer, Character, Real numbers etc
b) Non –primitive data structures
Non-primitive data types are not defined by the programming language, but are
instead created by the programmer.

Linear and Non-linear Data structures

Data structures are classified as

1)linear data structures

A data structure is said to be linear if its elements form a sequence or a linear list. In a linear
data structure, every data element has a unique successor and predecessor. There are two
basic ways of representing linear structures in memory. One way is to have the relationship
between the elements by means of pointers (links), called linked lists. The other way is using
sequential organization, that is, arrays

ii) Non linear non-linear.

Non-linear data structures are used to represent the data containing hierarchical or network
relationship among the elements. Trees and graphs are examples of non-linear data structures.
In non-linear data structures, every data element may have more than one predecessor as well
as successor. Elements do not form any particular linear sequence.

LINEAR DATA STRUCTURES

ARRAYS

• Array is a group of same type of variables that have common name

• Each item in the group is called an element of the array

• Each element is distinguished from another by an index

• All elements are stored contiguously in memory

• The elements of the array can be of any valid type- integers, characters, floating point types
or user-defined types

Types of Array:

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 12


1). One dimensional array: The elements of the array can be represented either as a single
column or as a single row.

Declaring one-dimensional array: data_type array_name[size];

Following are some valid array declarations: int age[15]; float weight[50];

Array Initialization (1-D):

The general format of array initialization is:

data_type array_name[size]={element1,element2,…………..,element n};

for example: int age[5]={22,33,43,24,55};

int weight[]={55,6,77,5,45,88,96,11,44,32};

float a[]={2,3.5,7.9,-5.9,-8};

char section[4]={‘A’,’B’,’C’,’D’};

char name[10]=”Bhupendra”;

A program to read n numbers and to find the sum and average of those numbers.

#include <iostream>

using namespace std;

int main()

int n, i;

float num[20], sum=0.0, average;

cout << "Enter array size: ";

cin >> n;

for(i = 0; i < n; ++i)

cout << i + 1 << ". Enter number: ";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 13


cin >> num[i];

sum += num[i];

average = sum / n;

cout << "Average = " << average;

return 0;

Some common operations performed in one-dimensional array are:

• Creating of an array

• Inserting new element at required position

• Deletion of any element

• Modification of any element

• Traversing of an array

• Merging of arrays

Insertion of new element at required position:

Let we have an array a[6]=(1,5,7,6,22,90};

Suppose we want to insert 20 in array a, at location with index 4, it means the elements 22
and 90 must shift 1 position downwards as follows.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 14


#include <iostream>

using namespace std;

int* insertX(int n, int arr[], int x, int pos)

int i;

// increase the size by 1

n++;

// shift elements forward

for(i = n; i >= pos; i--)

arr[i] = arr[i - 1];

// insert x at pos

arr[pos - 1] = x;

return arr;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 15


int main()

int arr[100] = { 0 };

int i, x, pos, n = 10;

// initial array of size 10

for (i = 0; i < 10; i++)

arr[i] = i + 1;

// print the original array

for (i = 0; i < n; i++)

cout << arr[i] << " ";

cout << endl;

// element to be inserted

x = 50; // position at which element is to be inserted

pos = 5;

// Insert x at pos

insertX(n, arr, x, pos);

// print the updated array

for (i = 0; i < n + 1; i++)

cout << arr[i] << " ";

cout << endl;

return 0;

Deletion of any element from an array:

Suppose we want to delete the element a[5]=90, then the elements following it were moved
upward by one location as shown in fig. below:

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 16


#include<iostream>

using namespace std;

int main()

int a[100], size, pos, i, count = 0;

cout << "Enter the size of an array \n";

cin >> size;

cout << "Enter the values in an array \n"; // Take an input array

for (i = 0; i < size; i++)

cin >> a[i];

//Input position where we delete an element

cout << "Enter the position \n";

cin >> pos;

//Shift element from i+1 to i

for(i = pos-1; i < size; i++)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 17


{

a[i] = a[i+1];

// Reduce the size of an array size--;

// Print an array after deleting an element

for(i = 0; i < size; i++)

cout<<" "<<a[i];

return 0;

REVERSE ELEMENTS OF AN ARRAY

#include<iostream>

using namespace std;

int main()

int arr[100], size, i, j, temp;

cout<<"\n Enter Array Size : ";

cin>>size;

cout<<"\n Enter Array Elements : \n";

for(i=0; i<size; i++)

cin>>arr[i];

cout<<"\n Array Elements : \n\n";

for(i=0; i<size; i++)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 18


cout<<arr[i]<<"\t";

j=i-1;//j points to the last element and i points to the first element

i=0;

while(i<j)

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

i++;

j--;

cout<<"\n\n Reverse Array Elements : \n\n";

for(i=0; i<size; i++)

cout<<arr[i]<<"\t";

return 0;

Traversing of an array:

Traversing means to access all the elements of the array, starting from first element upto the
last element in the array one-by-one.

NOTE

Consider your own example to traverse an array

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 19


Merging of two arrays:

Merging means combining elements of two arrays to form a new array. Simplest way of
merging two arrays is the first copy all elements of one array into a third empty array, and
then copy all the elements of other array into third array. Suppose we want to merge two
arrays a[6] and b[4]. The new array says c will be having (6+4) =10 elements as shown in
figure below.

EXAMPLE

#include<iostream>

using namespace std;

int main()

int arrOne[50], arrTwo[50], arrMerge[100];

int array1, array2, i, k;

cout<<"Enter the Size for First Array: ";

cin>>array1;

cout<<"Enter "<<array1<<" Elements for First Array: ";

for(i=0; i<array1; i++)

cin>>arrOne[i];

arrMerge[i] = arrOne[i];

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 20


}

k = i;

cout<<"\nEnter the Size for Second Array: ";

cin>>array2;

cout<<"Enter "<<array2<<" Elements for Second Array: ";

for(i=0; i<array2; i++)

cin>>arrTwo[i];

arrMerge[k] = arrTwo[i];

k++;

cout<<"\nThe New Array (Merged Array):\n";

for(i=0; i<k; i++)

cout<<arrMerge[i]<<" ";

cout<<endl;

return 0;

SEARCH AN ELEMENT IN AN ARRAY

#include<iostream>

using namespace std;

int main()

int arr[10], i, num, n, cnt=0, pos;

cout<<"\n Enter Array Size : ";

cin>>n;

cout<<"\n Enter Array Elements : \n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 21


for(i=0; i<n; i++)

cout<<" ";

cin>>arr[i];

cout<<"\n Enter Element to be Searched : ";

cin>>num;

for(i=0; i<n; i++)

if(arr[i]==num)

cnt=1;

pos=i+1;

break;

if(cnt==0)

cout<<"\n Element Not Found..!!";

else

cout<<"\n Element "<<num<<" Found At Position "<<pos;

return 0;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 22


SORT ARRAY ELEMENTS IN AN ASCENDING ORDER

/*Simple Sorting In Array (Asending Order) In C++*/

#include <iostream>

#include<conio.h>

using namespace std;

#define ARRAY_SIZE 5

int main()

int numbers[ARRAY_SIZE], i ,j ,temp;

cout<<"Sorting in Asending Order In Array\n";

// Read Input

for (i = 0; i < ARRAY_SIZE; i++)

cout<<"Enter the Number : "<< (i+1) <<" : ";

cin>>numbers[i]; } // Array Sorting - Asensding Order

for (i = 0; i < ARRAY_SIZE; ++i)

for (j = i + 1; j < ARRAY_SIZE; ++j)

if (numbers[i] > numbers[j])

temp = numbers[i];

numbers[i] = numbers[j];

numbers[j] = temp;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 23


cout<<"Sorting Order Array: \n";

for (i = 0; i < ARRAY_SIZE; ++i)

cout<<numbers[i]<<endl;

getch();

return 0;

SORT ARRAY ELEMENTS IN DESCENDING ORDER

#include<iostream>

using namespace std;

int main ()

int num[10];

int i, j, desc;

cout<<"\n Enter 10 Numbers : \n";

cout<<" ";

for (i = 0; i < 10; ++i)

cin>>num[i];

for (i = 0; i < 10; ++i)// 'for' loop is used for sorting the numbers in descending order

for (j = i + 1; j < 10; ++j)

if (num[i] < num[j])

desc = num[i];

num[i] = num[j];

num[j] = desc;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 24


}

cout<<"\n Numbers in Descending Order : \n";

for (i = 0; i < 10; ++i)

cout<<" ";

cout<<num[i];

cout<<"\n";

Two-Dimensional array:

When we declare two dimensional array, the first subscript written is for the number of rows
and the second one is for the column.

Declaration of 2- D array: Return_type array_name[row_size][column_size];

Example; int a[3][4]; float b[10][10];

int this first example, 3 represents number of rows and 4 represents number of columns.

• Think, two-dimensional arrays as tables/matrices arranged in rows and columns

• Use first subscript to specify row no and the second subscript to specify column no.

Array Initialization (2-D):

The general format of array initialization is:

data_type array_name[row_size][col_size]={element1,element2,…………..,element n};

for example: int a[2][3]={33,44,23,56,77,87};

or int a[2][3]={{33,44,23}, {56, 77, 87}};

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 25


Implementation of a two-dimensional array:

A two dimensional array can be implemented in a programming language in two ways:

• Row-major implementation

• Column-major implementation

Row-major implementation: Row-major implementation is a linearization technique in which


elements of array are reader from the keyboard row-wise i.e. the complete first row is stored,
and then the complete second row is stored and so on. For example, an array a[3][3] is stored
in the memory as shown in fig below:

Column-major implementation: In column major implementation memory allocation is done


column by column i.e. at first the elements of the complete first column is stored, and then
elements of complete second column is stored, and so on. For example an array a [3] [3] is
stored in the memory as shown in the fig below:

EXAMPLE

ADDITION OF TWO MATRICES

#include<iostream>

using namespace std;

int main()

int m1[3][3], m2[3][3], i, j, m3[3][3];

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 26


cout<<"\n Enter First Matrix Elements : \n";

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cout<<" ";

cin>>m1[i][j];

cout<<"\n Enter Second Matrix Elements : \n";

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cout<<" ";

cin>>m2[i][j];

cout<<"\n Sum of Two Matrices : \n\n";

for(i=0; i<3; i++)

for(j=0; j<3; j++)

m3[i][j]=m1[i][j]+m2[i][j];

for(i=0; i<3; i++)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 27


{

cout<<" ";

for(j=0; j<3; j++)

cout<<m3[i][j]<<" ";

cout<<"\n";

return 0;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 28


LIST ABSTACT DATA TYPE

List is basically the collection of elements arranged in a sequential manner.

In memory we can store the list in two ways:

• one way is we can store the elements in sequential memory locations. That
means we can store the list in arrays.
• The other way is we can use pointers or links to associate elements sequentially. This
is known as linked list.

LINKED LISTS

The linked list is very flexible dynamic data structure : items may be added to it or deleted
from it at will. A programmer need not worry about how many items a program will have to
accommodate in advance. This allows us to write robust programs which require much less
maintenance.

The linked allocation has the following draw backs:

1. No direct access to a particular element.

2. Additional memory required for pointers.

Linked list are of 3 types:

a). Singly Linked List

b). Doubly Linked List

c). Circularly Linked List

a. SINGLY LINKED LIST

A singly linked list, or simply a linked list, is a linear collection of data items. The linear
order is given by means of POINTERS. These types of lists are often referred to as linear
linked list.

Each item in the list is called a node.

Each node of the list has two fields:

1. Information- contains the item being stored in the list.

2. Next address- contains the address of the next item in the list.

The last node in the list contains NULL pointer to indicate that it is the end of the list

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 29


To create a linked list, following steps are required :-

1. Declare a structure that defines the list elements.

2. Within the structure body declare the variable(s) of each node that will contain information
and the pointer of each node.

3. Declare the external pointer and the node(s) of that structure type. A node may contain any
number of information fields.

Declaration syntax

struct node {
int data;
struct node *next;
}

example

Struct slinklist

int data;

struct slinklist* next;

};

typedef struct slinklist node;

node *start = NULL;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 30


Operations on Singly linked list:

• Creation
• Insertion of a node
• Deletions of a node
• Traversing the list

Creating a node for Single Linked List

Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated
for creating a node. The information is stored in the memory, allocated by using the new ()
function. The function getnode(), is used for creating a node, after allocating memory for the
node, the Information for the node at a path as to be read from the user and set next field to
NULL and finally return the node.

node* getnode()

node* newnode;

newnode = new node;

cout<< Enter data;

cin>> newnode-> data

newnode -> next = NULL;

return newnode;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 31


Creating a Singly Linked List with„ n‟ number of nodes

The following steps are to befollowed to create „n‟ number of nodes.

1. Get the new node using getnode().


newnode = getnode();
2. If the list is empty, assign new node as start.
start = newnode;
3. If the list is not empty, follow the steps given below. 
The next field of the newnode is made to point the first node (i.e. start node) in the list
by assigning the address of the first node.  The start pointer is made to point the
newnode by assigning the address of the new node.
4. Repeat the above steps „n‟ times.

Void createlist(int n)
{
int i;
node *newnode;
node *temp;
for(i = 0; i< n ; i++)
{
newnode = getnode();
if(start = = NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
}

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 32


Insertions:
To place an elements in the list there are 3 cases :
1. At the beginning /front
2. End of the list
3. At a given position

INSERTING A NODE AT THE BEGINNING

The following steps are to be followed to insert a new node at the

beginning of the list:

1. Get the new node using getnode() then new node = getnode();

2. If the list is empty then start = newnode.

3. If the list is not empty, follow the steps given below:

newnode -> next = head;

head = newnode;

head is the pointer variable which contains address of the first node and temp
contains address of new node to be inserted then sample code is

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 33


Void insert_at_beg()

node *newnode;

newnode = getnode();

if(start == NULL)

start = newnode;

else

newnode-> next = start;

start = newnode;

Insert node at the front/beginning example 2

void insertAtFront(int num) {

/* Create a new Linked List node */

struct node* newNode =new node;

newNode->data = num;

/* Next pointer of new node will point to head node of linked list */

newNode->next = head;

/* make new node as new head of linked list */

head = newNode;

cout<<"Inserted Element"<<num;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 34


INSERTING A NODE AT THE END
The following steps are followed to insert a new node at the end of the
list:
1. Get the new node using getnode() then newnode = getnode();
2. If the list is empty then start = newnode.
3. If the list is not empty follow the steps given below:
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;

head is the pointer variable which contains address of the first node and temp
contains address of new node to be inserted then sample code is

Void insert_at_end()
{
node *newnode, *temp;
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 35


Insert node at the end example 2
void insertAtEnd(struct node* head, int num){
/* Input validation */
if (head == NULL) {
cout<<"Error : Invalid node pointer";
return;
}
/* creates a new node */
struct node* newNode =new node;
newNode->data = num;
newNode->next = NULL;
/* Traverse from head to last node */
while(head->next != NULL)
head = head->next;

/* Insert newNode after Tail node */


head->next = newNode;
}

INSERTING A NODE AT SPECIFIED POSITION


The following steps are followed, to insert a new node in an
intermediate position in the list:
1. Get the new node using getnode() then newnode = getnode();
2.Ensure that the specified position is in between first node and last node. If
not, specified position is invalid. This is done by countnode() function.
3.Store the starting address (which is in start pointer) in temp and prev
pointers. Then traverse the temp pointer up to the specified position followed
by prev pointer.
4. After reaching the specified position, follow the steps given below:
prev -> next = newnode;
newnode-> next = temp;

example

Void insert_at_mid()
{
node *newnode, *temp, *prev;
int pos, nodectr, ctr = 1;
newnode = getnode();
cout<< Enter the position;
cin>>pos;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 36


nodectr = countnode(start);
if(pos> 1 &&pos<nodectr) {
temp = prev = start;
while(ctr<pos)
{
prev = temp;
temp = temp -> next;
ctr++;
}
prev -> next = newnode;
newnode -> next = temp;
}
else
{
cout<<pos;
}
}

Insert before or middle


void before( )
{
struct node *t,*p,*q;
int i,pos,count;
t=new node;
cout<<"\ntotal no of nodes are in list %d\n"<<count;
cout<<"\nenter the position to insert";
cin>>pos;
cout<<"\nenter any no:";
cin>>t->data;
t->next=NULL;
p=head;
if(pos == 1)
{
t->next=p; head=t;
}
else
{ for(i=1;i<pos-1;i++)
p=p->next;
q=p->next;
t->next =q;
p->next =t;
}
count++;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 37


}
SINGLE LINKED LIST WITH INSERTION OPERATIONS EXAMPLE

Include <iostream>
using namespace std;

/* A structure of linked list node */


struct node {
int data;
struct node *next;
}
*head;

void initialize(){
head = NULL;
}
Inserts a node in front of a singly linked list.
*/
void insertAtFront(int num) {
/* Create a new Linked List node */
struct node* newNode =new node;
newNode->data = num;
/* Next pointer of new node will point to head node of linked list */
newNode->next = head;
/* make new node as new head of linked list */
head = newNode;
cout<<"Inserted Element"<<num;
}

Inserts a node after last node of linked list


*/
void insertAtEnd(struct node* head, int num){
/* Input validation */
if (head == NULL) {
cout<<"Error : Invalid node pointer";
return;
}
/* creates a new node */
struct node* newNode =new node;
newNode->data = num;
newNode->next = NULL;
/* Traverse from head to last node */
while(head->next != NULL)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 38


head = head->next;

/* Insert newNode after Tail node */


head->next = newNode;
}

void printLinkedList(struct node *nodePtr) {


cout<<"\nLinked List\n";
while (nodePtr != NULL) {
cout<<nodePtr->data;
nodePtr = nodePtr->next;
if(nodePtr != NULL)
cout<<"-->";
}
}
int main() {
initialize();
/* Creating a linked List*/
insertAtFront(2);
insertAtFront(4);
insertAtFront(5);
insertAtFront(9);
printLinkedList(head);
void before();
/* Inserting a node after tail node of Linked List */
insertAtEnd(head, 10);
cout<<"\n\nAfter Insertion At End\n";
printLinkedList(head);
return 0;
}

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 39


DELETION OF A NODE
Another operation that can be done in a singly linked list is the
deletion of a node. Memory is to be released for the node to be deleted. A
node can be deleted from the list from three different places.
• Deleting at beginning.
• Deleting a node at the end.
• Deleting a node at specified position.

DELETING A NODE AT THE BEGINNING

The following steps are followed, to delete a node at the beginning of

the list:

1.If list is empty then display „EmptyList‟ message.

2.If the list is not empty, follow the steps given below:

temp = start;

start = start -> next;

delete temp;

EXAMPLE

void delete_at_beg()

node *temp;

if(start == NULL)

cout<< “No nodes are exist”;

return ;

else

temp = start;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 40


start = temp -> next;

delete temp;

cout<<Node deleted;

DELETING A NODE AT THE END

The following steps are followed to delete a node at the end of the list:

1. If list is empty then display „EmptyList‟ message.

2. If the list is not empty, follow the steps given below:

temp = prev = start;

while(temp -> next != NULL)

prev = temp;

temp = temp -> next;

prev -> next = NULL;

delete temp;

EXAMPLE

Void delete_at_last()

node *temp, *prev;

if(start == NULL)

cout<<Empty List;

return ;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 41


}

else

temp = start;

prev = start;

while(temp -> next != NULL)

prev = temp;

temp = temp -> next;

prev -> next = NULL;

delete temp;

cout<<Node deleted;

DELETING A NODE AT SPECIFIED POSITION

The following steps are followed, to delete node from the specified

position in the list.

1. If list is empty then display „EmptyList‟ message

2. If the list is not empty, follow the steps given below.

if(pos> 1 &&pos<nodectr) {

temp = prev = start;

ctr = 1;

while(ctr<pos) {

prev = temp;

temp = temp -> next;

ctr++;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 42


}

prev -> next = temp -> next;

delete temp;

cout<<node deleted;

EXAMPLE

Void delete_at_mid()

intctr = 1, pos, nodectr;

node *temp, *prev;

if(start == NULL)

cout<<Empty List;

return ;

else

cout<<Enter position of node to delete;

cin>>pos;

nodectr = countnode(start);

if(pos>nodectr)

cout<<This node does not exist;

if(pos> 1 &&pos<nodectr) {

temp = prev = start;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 43


while(ctr<pos)

prev = temp;

temp = temp -> next;

ctr ++;

prev -> next = temp -> next;

delete temp;

cout<<Node deleted;

else

cout<<Invalid position;

TRAVERSAL AND DISPLAYING A LIST (LEFT TO RIGHT)

To display the information, you have to traverse (move) a linked list,

node by node from the first node, until the end of the list is reached.

Traversing a list involves thefollowing steps.

1. Assign the address of start pointer to a temp pointer.

2. Display the information from the data field of each node.

The function traverse () is used for traversing and displaying the

information stored in the list from left to right.

EXAMPLE

void traverse()

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 44


{

node *temp;

temp = start;

cout<<The contents of List (Left to Right);

if(start == NULL )

cout<<Empty List;

else

while (temp != NULL)

cout<<temp -> data;

temp = temp -> next;

cout<<X;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 45


b). DOUBLY LINKED LIST
A singly linked list has the disadvantage that we can only traverse it in one direction. Many
applications require searching backwards and forwards through sections of a list.
A useful refinement that can be made to the singly linked list is to create a doubly linked list.
The distinction made between the two list types is that while singly linked list have pointers
going in one direction, doubly linked list have pointer both to the next and to the previous
element in the list.

The main advantage of a doubly linked list is that, they permit traversing or searching of the
list in both directions.

In this linked list each node contains three fields.


a) One to store data
b) Remaining are self referential pointers which points to previous and next nodes in the list

Implementation of Doubly Linked List

Before writing the code to build the list, we need to create a start node, used to create and
access other nodes in the linked list.

• Creating a structure with one data item and a right pointer, which will

be pointing to next node of the list and left pointer pointing to the previous node. This is
called as self-referential structure.

• Initialize the start pointer to be NULL.

Struct dlinklist

struct dlinklist * left;

int data;

struct dlinklist * right;

};

typedef struct dlinklist node;

node *start = NULL;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 46


Basic operation performed on doubly linked list

The different operations performed on the doubly linked list are listed as follows.

• Creation
• Insertion
• Deletion
• Traversing
• Display

Creating a node for Doubly Linked List

Creating a doubly linked list starts with creating a node. Sufficient memory has to be
allocated for creating a node. The information is stored in the memory, allocated by using the
new() function.

The function getnode(),is used for creating a node, after allocating memory for the node, the
information for the node data part has to be read from the user and set left and right field to
NULL and finally return the node.

node* getnode()

node* newnode;

newnode = new node;

cout<< Enter data;

cin>>newnode-> data

newnode -> left = NULL;

newnode -> right = NULL;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 47


return newnode;

Creating a Doubly Linked List with „n‟ number of nodes

The following steps are to be followed to create „n‟ number of nodes.

1. Get the new node using getnode().

newnode = getnode();

2. If the list is empty, assign new node as start.

start = newnode;

3. If the list is not empty, follow the steps given below.

• The left field of the new node is made to point the previous node.
• The previous nodes right field must be assigned with address of the new node.
5. Repeat the above steps „n‟ times.

The function createlist(), is used to create „n‟ number of nodes

void createlist(int n)

int i;

node *newnode;

node *temp;

for(i = 0; i< n ; i++) {

newnode = getnode();

if(start = = NULL)

start = newnode;

else

temp = start;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 48


while(temp -> right != NULL)

temp = temp -> right;

temp -> right = newnode;

newnode -> left = temp;

INSERTION OF A NODE

One of the most important operations that can be done in a doubly linked list is the insertion
of a node . Memory is to be allocated for the new node before reading the data .The new node
will contain empty data field and empty next field. The data field of the new node is then
stored with the information read from the user .The left and right fields of the new node are
set to NULL. The new node can then be inserted at three different places

namely:

• Inserting a node at the beginning.


• Inserting a node at the end.
• Inserting a node at specified position.

INSERTING A NODE AT THE BEGINNING

The following steps are to be followed to insert a newnode at the beginning of the list:

1.Get the new node using getnode() then

newnode = getnode();

2. If the list is empty then start = newnode.

3. If the list is not empty, follow the steps given below:

newnode -> right = start;

start -> left = newnode;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 49


start = newnode;

EXAMPLE

void insertion_beginning()

struct node *ptr;

int item;

ptr = new node;

if(ptr == NULL)

cout<<"\nOVERFLOW";

else

cout<<"\nEnter Item value";

cin>>item;

if(head==NULL)

ptr->next = NULL;

ptr->prev=NULL;

ptr->data=item;

head=ptr;

else

ptr->data=item;

ptr->prev=NULL;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 50


ptr->next = head;

head->prev=ptr;

head=ptr;

cout<<"\nNode inserted\n";

INSERTING A NODE AT THE END

The following steps are followed to insert a newnode at the end of the

list:

1. Get the new node using getnode() then newnode = getnode();

2. If the list is empty then start = newnode.

3. If the list is not empty follow the steps given below:

temp = start;

while(temp -> right != NULL)

temp = temp -> right;

temp -> right = newnode;

newnode -> left = temp;

void insertion_last()

struct node *ptr,*temp;

int item;

ptr = new node;

if(ptr == NULL)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 51


cout<<"\nOVERFLOW";

else

cout<<"\nEnter value";

cin>>item;

ptr->data=item;

if(head == NULL)

ptr->next = NULL;

ptr->prev = NULL;

head = ptr;

else

temp = head;

while(temp->next!=NULL)

temp = temp->next;

temp->next = ptr;

ptr ->prev=temp;

ptr->next = NULL;

cout<<"\nnode inserted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 52


}

EXAMPLE

INSERTING A NODE AT SPECIFIED POSITION

The following steps are followed, to insert a new node in an

intermediate position in the list:

1. Get the new node using getnode() then newnode = getnode();

2.Ensure that the specified position is in between first node and last node. If

not, specified position is invalid. This is done by countnode() function.

3.Store the starting address (which is in start pointer)in temp and prev

pointers. Then traverse the temp pointer up to the specified position followed

by prev pointer.

4. After reaching the specified position, follow the steps given below:

newnode -> left = temp;

newnode ->right= temp->right;

temp -> right ->left = newnode;

temp-> right= newnode;

EXAMPLE

void insertion_specified()

struct node *ptr,*temp;

int item,loc,i;

ptr = new node;

if(ptr == NULL)

cout<<"\n OVERFLOW";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 53


}

else

temp=head;

cout<<"Enter the location";

cin>>loc;

for(i=0;i<loc;i++)

temp = temp->next;

if(temp == NULL)

cout<<"\n There are less than %d elements"<< loc;

return;

cout<<"Enter value";

cin>>item;

ptr->data = item;

ptr->next = temp->next;

ptr -> prev = temp;

temp->next = ptr;

temp->next->prev=ptr;

cout<<"\nnode inserted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 54


DELETION OF A NODE

Another operation that can be done in a doubly linked list is the deletion of a node. Memory
is to be released for the node to be deleted. A node can be deleted from the list from three
different places.

• Deleting a node at the beginning.


• Deleting a node at the end.
• Deleting a node at specified position

DELETING A NODE AT THE BEGINNING

The following steps are followed ,to delete a node at the beginning of

the list:

1.If list is empty then display „EmptyList‟ message.

2.If the list is not empty, follow the steps given below:

temp = start;

start = start -> right;

start -> left = NULL;

delete temp;

EXAMPLE

void deletion_beginning()

struct node *ptr;

if(head == NULL)

cout<<"\n UNDERFLOW OR LIST EMPTY";

else if(head->next == NULL)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 55


{

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

ptr = head;

head = head -> next;

head -> prev = NULL;

delete ptr;

cout<<"\nnode deleted\n";

DELETING A NODE AT THE END

The following steps are followed to delete a node at the end of the list:

1. If list is empty then display „EmptyList‟ message.

2. If the list is not empty, follow the steps given below:

temp = start;

while(temp -> right != NULL)

temp = temp ->right;

temp –> left -> right = NULL;

delete temp;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 56


EXAMPLE

void deletion_last()

struct node *ptr;

if(head == NULL)

cout<<"\n UNDERFLOW";

else if(head->next == NULL)

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

ptr = head;

if(ptr->next != NULL)

ptr = ptr -> next;

ptr -> prev -> next = NULL;

delete ptr;

cout<<"\nnode deleted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 57


DELETING A NODE AT SPECIFIED POSITION

The following steps are followed,to delete a node from the specified position in

the list.

1. If list is empty then display „EmptyList‟ message

2. If the list is not empty, follow the steps given below.

if(pos> 1 &&pos<nodectr) {

temp = start;ctr= 1;

while(ctr<pos) {

temp = temp -> right;

ctr++;

temp -> right -> left = temp ->left;

temp -> left -> right = temp -> right;

delete temp;

EXAMPLE

void deletion_specified()

struct node *ptr, *temp;

int val;

cout<<"\n Enter the data after which the node is to be deleted : ";

cin>>val;

ptr = head;

while(ptr -> data != val)

ptr = ptr -> next;

if(ptr -> next == NULL)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 58


cout<<"\nCan't delete\n";

else if(ptr -> next -> next == NULL)

ptr ->next = NULL;

else

temp = ptr -> next;

ptr -> next = temp -> next;

temp -> next -> prev = ptr;

delete temp;

cout<<"\nnode deleted\n";

TRAVERSAL AND DISPLAYING A LIST(LEFT TO RIGHT)

To display the information, you have to traverse the list, node by node from the first node
,until the end of the list is reached .The function traverse_left_right() is used for traversing
and displaying the information stored in the list from left to right. The following steps are
followed, to traverse a list from left to right:

1. If list is empty then display „EmptyList‟ message.2.

If the list is not empty, follow the steps given below:

temp = start;

while(temp != NULL)

cout<<temp -> data;

temp = temp -> right;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 59


EXAMPLE

void display()

struct node *ptr;

cout<<"\n printing values...\n";

ptr = head;

while(ptr != NULL)

cout<<ptr->data;

ptr=ptr->next;

TRAVERSAL AND DISPLAYING A LIST (RIGHT TO LEFT)

To display the information from right to left, you have to traverse the list, node by node from
the first node, until the end of the list is reached. The function traverse_right_left() is used for
traversing and displaying the information stored in the list from right to left .The following
steps are followed, to traverse a list from right to left:

1. If list is empty then display „EmptyList‟ message.2.

If the list is not empty, follow the steps given below:

temp = start;

while(temp -> right != NULL)

temp = temp -> right;

while(temp != NULL)

cout<< temp -> data;

temp = temp -> left;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 60


}

DOUBLE LINKED LIST AND ITS OPERATIONS FULL CODE EXAMPLE

#include<iostream>

using namespace std;

struct node

struct node *prev;

struct node *next;

int data;

};

struct node *head;

void insertion_beginning();

void insertion_last();

void insertion_specified();

void deletion_beginning();

void deletion_last();

void deletion_specified();

void display();

void search();

int main ()

int choice =0;

while(choice != 9)

cout<<"\n*********Main Menu*********\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 61


cout<<"\nChoose one option from the following list ...\n";

cout<<"\n===============================================\n";

cout<<"\n1.Insert in begining\n2.Insert at last\n3.Insert at any random


location\n4.Delete from Beginning\n5.Delete from last\n6.Delete the node after the given
data\n7.Search\n8.Show\n9.Exit\n";

cout<<"\nEnter your choice?\n";

cin>>choice;

switch(choice)

case 1:

insertion_beginning();

break;

case 2:

insertion_last();

break;

case 3:

insertion_specified();

break;

case 4:

deletion_beginning();

break;

case 5:

deletion_last();

break;

case 6:

deletion_specified();

break;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 62


case 7:

search();

break;

case 8:

display();

break;

case 9:

exit(0);

break;

default:

cout<<"Please enter valid choice..";

void insertion_beginning()

struct node *ptr;

int item;

ptr = new node;

if(ptr == NULL)

cout<<"\nOVERFLOW";

else

cout<<"\nEnter Item value";

cin>>item;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 63


if(head==NULL)

ptr->next = NULL;

ptr->prev=NULL;

ptr->data=item;

head=ptr;

else

ptr->data=item;

ptr->prev=NULL;

ptr->next = head;

head->prev=ptr;

head=ptr;

cout<<"\nNode inserted\n";

void insertion_last()

struct node *ptr,*temp;

int item;

ptr = new node;

if(ptr == NULL)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 64


cout<<"\nOVERFLOW";

else

cout<<"\nEnter value";

cin>>item;

ptr->data=item;

if(head == NULL)

ptr->next = NULL;

ptr->prev = NULL;

head = ptr;

else

temp = head;

while(temp->next!=NULL)

temp = temp->next;

temp->next = ptr;

ptr ->prev=temp;

ptr->next = NULL;

cout<<"\nnode inserted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 65


}

void insertion_specified()

struct node *ptr,*temp;

int item,loc,i;

ptr = new node;

if(ptr == NULL)

cout<<"\n OVERFLOW";

else

temp=head;

cout<<"Enter the location";

cin>>loc;

for(i=0;i<loc;i++)

temp = temp->next;

if(temp == NULL)

cout<<"\n There are less than %d elements"<< loc;

return;

cout<<"Enter value";

cin>>item;

ptr->data = item;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 66


ptr->next = temp->next;

ptr -> prev = temp;

temp->next = ptr;

temp->next->prev=ptr;

cout<<"\nnode inserted\n";

void deletion_beginning()

struct node *ptr;

if(head == NULL)

cout<<"\n UNDERFLOW OR LIST EMPTY";

else if(head->next == NULL)

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

ptr = head;

head = head -> next;

head -> prev = NULL;

delete ptr;

cout<<"\nnode deleted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 67


}

void deletion_last()

struct node *ptr;

if(head == NULL)

cout<<"\n UNDERFLOW";

else if(head->next == NULL)

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

ptr = head;

if(ptr->next != NULL)

ptr = ptr -> next;

ptr -> prev -> next = NULL;

delete ptr;

cout<<"\nnode deleted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 68


}

void deletion_specified()

struct node *ptr, *temp;

int val;

cout<<"\n Enter the data after which the node is to be deleted : ";

cin>>val;

ptr = head;

while(ptr -> data != val)

ptr = ptr -> next;

if(ptr -> next == NULL)

cout<<"\nCan't delete\n";

else if(ptr -> next -> next == NULL)

ptr ->next = NULL;

else

temp = ptr -> next;

ptr -> next = temp -> next;

temp -> next -> prev = ptr;

delete temp;

cout<<"\nnode deleted\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 69


void display()

struct node *ptr;

cout<<"\n printing values...\n";

ptr = head;

while(ptr != NULL)

cout<<ptr->data;

ptr=ptr->next;

void search()

struct node *ptr;

int item,i=0,flag;

ptr = head;

if(ptr == NULL)

cout<<"\nEmpty List\n";

else

cout<<"\nEnter item which you want to search?\n";

cin>>item;

while (ptr!=NULL)

if(ptr->data == item)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 70


{

cout<<"\nitem found at location ",i+1;

flag=0;

break;

else

flag=1;

i++;

ptr = ptr -> next;

if(flag==1)

cout<<"\nItem not found\n";

c) CIRCULAR LISTS

Circular linked list is a linked list which consists of collection of nodes each of which has two
parts, namely the data part and the next part. The data part holds the value of the element and
the next part has the address of the next node. The last node of list has the next pointing to the
first node thus making the circular traversal possible in the list.

It is just a single linked list in which the next field of the last node points back to the address
of the first node. A circular linked list has no beginning and no end. In circular linked list no
null pointers are used, hence all pointers contain valid address.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 71


Advantages:
• Any node can be traversed starting from any other node in the list.
• There is no need of NULL pointer to signal the end of the list and hence, all pointers
contain valid addresses.
• In contrast to singly linked list, deletion operation in circular list is simplified as the
search for the previous node of an element to be deleted can be started from that item
itself.

Creating a node for Circular Linked List

Creating a circular linked list starts with creating a node. Sufficient memory has to be
allocated for creating a node. The information is stored in the memory, allocated by using the
new() function. The function getnode(),is used for creating a node, after allocating memory
for the node, the information for the node data part has to be read from the user and set next
field to NULL and finally return the node.

node* getnode()

node* newnode;

newnode = new node;

cout<< Enter data;

cin>>newnode-> data

newnode -> next = NULL;

return newnode;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 72


Creating a Circular Linked List with „n‟ number of nodes

The following steps are to befollowed to create „n‟ number of nodes.

1. Get the new node using getnode().

newnode = getnode();

2. If the list is empty, assign new node as start.

start = newnode;

3. If the list is not empty, follow the steps given below.

temp = start;

while(temp -> next != NULL)

temp = temp -> next;

temp -> next = newnode;

4. Repeat the above steps „n‟times.

5. newnode -> next = start;

EXAMPLE

Void createlist(int n)

inti;

node *newnode;

node *temp;

for(i = 0; i< n ; i++) {

newnode = getnode();

if(start = = NULL)

start = newnode;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 73


else

temp = start;

while(temp -> next != NULL)

temp = temp -> next;

temp -> next = newnode;

newnode -> next = start;

INSERTING A NODE AT THE BEGINNING

The following steps are to be followed to insert a new node at the

beginning of the circular list:

1. Get the new node using getnode ().

newnode = getnode();

2. If the list is empty, assign new node as start.

start = newnode;

newnode -> next = start;

3. If the list is not empty, follow the steps given below:

last = start;

while(last -> next != start)

last = last -> next;

newnode -> next = start;

start = newnode;

last -> next = start;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 74


INSERTING A NODE AT THE END

The following steps are followed to insert a new node at the end of the

list:

1. Get the new node using getnode().

newnode = getnode();

2. If the list is empty, assign new node as start.

start = newnode;

newnode -> next = start;

3. If the list is not empty follow the steps given below:

temp = start;

while(temp -> next != start)

temp = temp -> next;

temp -> next = newnode;

newnode -> next = start;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 75


EXAMPLE PROGRAM TO IMPLEMENT A CIRCULAR LINKED LIST

#include<iostream>

using namespace std;

struct node

int data;

struct node *next;

};

struct node *head;

void beginsert ();

void lastinsert ();

void randominsert();

void begin_delete();

void last_delete();

void random_delete();

void display();

void search();

int main ()

int choice =0;

while(choice != 7)

cout<<"\n*********Main Menu*********\n";

cout<<"\nChoose one option from the following list ...\n";

cout<<"\n===============================================\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 76


cout<<"\n1.Insert in begining\n2.Insert at last\n3.Delete from Beginning\n4.Delete from
last\n5.Search for an element\n6.Show\n7.Exit\n";

cout<<"\nEnter your choice?\n";

cin>>choice;

switch(choice)

case 1:

beginsert();

break;

case 2:

lastinsert();

break;

case 3:

begin_delete();

break;

case 4:

last_delete();

break;

case 5:

search();

break;

case 6:

display();

break;

case 7:

exit(0);

break;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 77


default:

cout<<"Please enter valid choice..";

void beginsert()

struct node *ptr,*temp;

int item;

ptr = new node;

if(ptr == NULL)

cout<<"\nOVERFLOW";

else

cout<<"\nEnter the node data?";

cin>>item;

ptr -> data = item;

if(head == NULL)

head = ptr;

ptr -> next = head;

else

temp = head;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 78


while(temp->next != head)

temp = temp->next;

ptr->next = head;

temp -> next = ptr;

head = ptr;

cout<<"\nnode inserted\n";

void lastinsert()

struct node *ptr,*temp;

int item;

if(ptr == NULL)

cout<<"\nOVERFLOW\n";

else

cout<<"\nEnter Data?";

cin>>item;

ptr->data = item;

if(head == NULL)

head = ptr;

ptr -> next = head;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 79


else

temp = head;

while(temp -> next != head)

temp = temp -> next;

temp -> next = ptr;

ptr -> next = head;

cout<<"\nnode inserted\n";

void begin_delete()

struct node *ptr;

if(head == NULL)

cout<<"\nUNDERFLOW";

else if(head->next == head)

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 80


{ ptr = head;

while(ptr -> next != head)

ptr = ptr -> next;

ptr->next = head->next;

delete head;

head = ptr->next;

cout<<"\nnode deleted\n";

void last_delete()

struct node *ptr, *preptr;

if(head==NULL)

cout<<"\nUNDERFLOW";

else if (head ->next == head)

head = NULL;

delete head;

cout<<"\nnode deleted\n";

else

ptr = head;

while(ptr ->next != head)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 81


preptr=ptr;

ptr = ptr->next;

preptr->next = ptr -> next;

delete ptr;

cout<<"\nnode deleted\n";

void search()

struct node *ptr;

int item,i=0,flag=1;

ptr = head;

if(ptr == NULL)

cout<<"\nEmpty List\n";

else

cout<<"\nEnter item which you want to search?\n";

cin>>item;

if(head ->data == item)

cout<<"item found at location %d",i+1;

flag=0;

else

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 82


{

while (ptr->next != head)

if(ptr->data == item)

cout<<"item found at location "<<i+1;

flag=0;

break;

else

flag=1;

i++;

ptr = ptr -> next;

if(flag != 0)

cout<<"Item not found\n";

void display()

struct node *ptr;

ptr=head;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 83


if(head == NULL)

cout<<"\nnothing to print";

else

cout<<"\n printing values ... \n";

while(ptr -> next != head)

cout<< ptr -> data<<"\n";

ptr = ptr -> next;

cout<<ptr -> data;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 84


STACK

A stack is an ordered collection of items into which new items may be inserted and from which items
may be deleted at one end, called the top of the stack. The deletion and insertion in a stack is done
from top of the stack. The following fig shows the stack containing items

This end is often known as top of stack. When an item is added to a stack, the operation is called
push, and when an item is removed from the stack the operation is called pop. Stack is also called as
Last- InFirst- Out (LIFO) list.

Every operation of the stack is performed at the top of the stack.

Operations on Stack:

a) a) create(s) - To create s as an empty stack.


b) b) push(s,i) - To insert the element I on top of the stack s.
c) c) pop(s) - To remove the top element of the stack and to return the removed element as a
function value.
d) d) top(s) - To return the top element of stack(s).
e) e) empty(s) - To check whether the stack is empty or not. It returns true if stack is empty and
returns false otherwise

consider the following basic important operations

PUSH operation:

The push operation is used to add (or push or insert) elements in a stack.

When we add an item to a stack, we say that we push it onto the stack .

The last item put into the stack is at the top

Conditions for push operation

1. Check stack is full or not?

I.e. top=Max

. Otherwise insert the element into the stack

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 85


b)POP operation:

The pop operation is used to remove or delete the top element from the stack.

When we remove an item, we say that we pop it from the stack.

When an item popped, it is always the top item which is removed.

We may notice that the last item pushed onto a stack is always the first that will be popped from the
stack. That is why stack is called last in, first out or LIFO in short.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 86


Implementation of Stack:
Stack can be implemented in two ways:
1. Array Implementation of stack (or static implementation)
2. Linked list implementation of stack (or dynamic)

Implementing a stack with an array:

Since a stack usually holds a bunch of items with the same type, we could implement a stack as an
array. Consider how we could have an array of characters, contents, to hold the contents of the
stack, and an integer top that holds the index of the element at the top of the stack.

We choose the array to be of size 4 for now. Starting with an empty stack, we have:

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 87


Implementation of push () operation

void push()

int x;

if(top == max-1)

cout<<"\n stack is overflow";

else

cout<<"enter element :";

cin>>x;

item[ ++top]=x;

Pop () : Pop is nothing but deleting the element from stack.

Conditions for pop operation

1 Check stack is empty or not?

I.e. top=-1

2. Otherwise delete the element from the stack

Now the stack is as follows

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 88


Implementation of pop () operation

void pop()

int x;

if(top ==-1)

cout<<"\n stack is under flow";

else

x = item[ top--];

cout<<"\n deleted element"<<x;

Peep ():or peek() Peep is nothing but display the elements at the top of stack

Condition for peep operation?

Check queue is empty or not?

I.e. top=-1

Otherwise display the element in the stack

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 89


Implementation of peep () operation

int peek()

int i;

if(top ==-1)

cout<<"\n stack is empty";

else

item[top];

A program that implement stack (its operations) using Arrays

#include<iostream>

using namespace std;

#define max 5

int top=-1;

int item[max];

int main( )

void push();

void pop();

int peek();

void display();

int n;

top=-1;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 90


while(1)

cout<<"\n 1. push";

cout<<"\n 2. pop";

cout<<"\n 3. peek";

cout<<"\n 4. display";

cout<<"\n 5. exit";

cout<<endl<<"choice :";

cin>>n;

switch(n)

case 1: push();

break;

case 2: pop();

break;

case 3: peek();

break;

case 4: exit (0);

default :cout<<"\n stack implementation using array";

void push()

int x;

if(top == max-1)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 91


cout<<"\n stack is overflow";

else

cout<<"enter element :";

cin>>x;

item[ ++top]=x;

void pop()

int x;

if(top ==-1)

cout<<"\n stack is under flow";

else

x = item[ top--];

cout<<"\n deleted element"<<x;

void display()

int i;

if(top>=0)

cout<<"elements in the stack are\n";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 92


for(i=0;i>top;i--)

cout<<item[i]<<"";

cout<<"\n";

else

cout<<"stack is empty";

int peek()

int i;

if(top ==-1)

cout<"\n stack is empty";

else

item[top];

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 93


Implementing a stack with a linked list:

The linked-list implementation is equally simple and straightforward. In fact, a stack linked-list is
much simpler than most linked-list implementations: it requires that we implement a linked-list
where only the head node or element can be removed, or popped, and a node can only be inserted
by becoming the new head node.

Unlike the array implementation, our structure typedef corresponds not to the entire stack
structure, but to a single node:

struct stack

int data;

struct stack *next;

stack

Using a linked list is one way to implement a stack so that it can handle essentially any number of
elements.

Push (): operation both initializes an empty stack, and adds a new node to a non-empty one. It works
by receiving a data value to push onto the stack, along with a target stack, creating a new node by
allocating memory for it, and then inserting it into a linked list as the new head.

Here is what a linked list implementing a stack with 3 elements might look like:

Pop (): operation removes the head from the linked list, and assigns the pointer to the head to the
previous second node. It check whether the list is empty before popping from it:

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 94


EXAMPLE PROGRAM TO IMPLEMENT A STACK USING A LINKED LIST

#include<iostream>

using namespace std;

struct node

int info;

struct node *ptr;

*top,*top1,*temp;

int topelement();

void push(int data);

void pop();

void empty();

void display();

void destroy();

void stack_count();

void create();

int count = 0;

int main()

int no, ch, e;

cout<<"\n 1 - Push";

cout<<"\n 2 - Pop";

cout<<"\n 3 - Top";

cout<<"\n 4 - Empty";

cout<<"\n 5 - Exit";

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 95


cout<<"\n 6 - Dipslay";

cout<<"\n 7 - Stack Count";

cout<<"\n 8 - Destroy stack";

create();

while (1)

cout<<"\n Enter choice :";

cin>>ch;

switch (ch)

case 1:

cout<<"Enter data :";

cin>>no;

push(no);

break;

case 2:

pop();

break;

case 3:

if (top == NULL)

cout<<"No elements in stack";

else

e = topelement();

cout<<"\n Top element is:"<<e;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 96


break;

case 4:

empty();

break;

case 5:

exit(0);

case 6:

display();

break;

case 7:

stack_count();

break;

case 8:

destroy();

break;

default :

cout<<"Wrong choice, Please enter correct choice ";

break;

/* Create empty stack */

void create()

top = NULL;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 97


/* Count stack elements */

void stack_count()

cout<<"\n No. of elements in stack are:"<<count;

/* Push data into stack */

void push(int data)

if (top == NULL)

top =new node;

top->ptr = NULL;

top->info = data;

else

temp =new node;

temp->ptr = top;

temp->info = data;

top = temp;

count++;

/* Display stack elements */

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 98


void display()

top1 = top;

if (top1 == NULL)

cout<<"Stack is empty";

return;

while (top1 != NULL)

cout<<top1->info<<endl;

top1 = top1->ptr;

/* Pop Operation on stack */

void pop()

top1 = top;

if (top1 == NULL)

cout<<"\n Error : Trying to pop from empty stack";

return;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 99


else

top1 = top1->ptr;

cout<<"\n Popped value is:"<<top->info;

delete top;

top = top1;

count--;

/* Return top element */

int topelement()

return(top->info);

/* Check if stack is empty or not */

void empty()

if (top == NULL)

cout<<"\n Stack is empty";

else

cout<<"\n Stack is not empty contains elements"<<count;

/* Destroy entire stack */

void destroy()

top1 = top;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 100


while (top1 != NULL)

top1 = top->ptr;

delete top;

top = top1;

top1 = top1->ptr;

delete top1;

top = NULL;

cout<<"\n All stack elements destroyed";

count = 0;

Applications of Stack:

Stack is used directly and indirectly in the following fields:

• To evaluate the expressions (postfix, infinix,prefix)


• To keep the page-visited history in a Web browser
• To perform the undo sequence in a text editor
• Used in recursion
• To pass the parameters between the functions in a C program
• Can be used as an auxiliary data structure for implementing algorithms
• Can be used as a component of other data structures

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 101


RECURSION
• Any programming language allows any of its functions to call itself multiple times in a
program. Here, any function that happens to call itself again and again (directly or
indirectly), unless the program satisfies some specific condition/subtask is called a recursive
function.
• Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.
• it is also a prerequisite that you choose a termination condition for the recursive function- or
else, the program will be stuck in a loop.
• Consider the stack, we will keep placing execution contexts on top of the stack. This may
happen until we have a “stack overflow”. A stack overflow is when we run out of memory to
hold items in the stack

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 102


EXAMPLE

PROGRAM TO FIND SUM OF NATURAL NUMBERS USING RECURSION

#include <iostream>

using namespace std;

int sum(int n);

int main() {

int number, result;

cout<<"Enter a positive integer:";

cin>>number;

result = sum(number);

cout<<result;

return 0;

int sum(int n) {

if (n != 0)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 103


// sum() function calls itself

return n + sum(n-1);

else

return n;

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to
the sum() function. This process continues until n is equal to 0.

When n is equal to 0, the if condition fails and the else part is executed returning the sum of integers
ultimately to the main() function.

EXAMPLE 2

FIND FACTORIAL OF A NUMBER USING RECURSION

#include<iostream>

using namespace std;

int fact(int a); /* Definition of Function */

int main()

int number, result;

cout<<"Please enter a non-negative number here:";

cin>>number;

result = fact(number); /* Function Calling in a Normal way */

cout<<"factotial of the number is:"<<result;

int fact(int a) /* Definition of Function */

int x=1;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 104


if(a <= 0)

return(1);

else

x = a * fact(a-1); /* Function Call Recursively as the fact() calls itself in the program */

return(x);

The output generated here from the code mentioned above would be: Please enter a non-
negative number here: 5

5! = 120

EXAMPLE 3

IMPLEMENT FIBONACCI SERIES

#include <iostream>

using namespace std;

// Function for fibonacci

int fib(int n)

// Stop condition

if (n == 0)

return 0;

// Stop condition

if (n == 1 || n == 2)

return 1;

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 105


// Recursion function

else

return (fib(n - 1) + fib(n - 2));

int main()

// Initialize variable n.

int n = 8;

cout<<"Fibonacci series of the numbers is:";

// for loop to print the fibonacci series.

for (int i = 0; i < n; i++) {

cout<<fib(i)<<endl;

return 0;

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is
usually much slower.

That being said, recursion is an important concept. It is frequently used in data structure and
algorithms For example, it is common to use recursion in problems such as tree traversal.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 106


QUEUE DATA STRUCTURE

A Queue is an ordered collection of items from which items may be deleted at one end
(called the front of the queue and into which items may be inserted at the other end (the
rear of the queue.

To understand a queue, think of a cafeteria line: the person at the front is served first, and
people are added to the line at the back. Thus, the first person in line is served first, and the
last person is served last.
This can be abbreviated to First In, First Out (FIFO).

The cafeteria line is one type of queue. Queues are often used in programming networks,
operating systems, and other situations in which many different processes must share
resources such as CPU time.
When inserting for the very first time, we need to adjust in position of front from zero to 1

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 107


Basic Operations

Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues −

1. enqueue() − add (store) an item to the queue.


2. dequeue() − remove an item from the queue.

Few more functions are required to make the above-mentioned queue operation efficient. These are

peek() − Gets the element at the front of the queue without removing it.

isfull() − Checks if the queue is full.

isempty() − Checks if the queue is empty

Queue operations work as follows:

1. Two pointers called FRONT and REAR are used to keep track of the first and last elements in the
queue.

2. When initializing the queue, we set the value of FRONT and REAR to 0.

3. On enqueing an element, we increase the value of REAR index and place the new element in the
position pointed to by REAR.

4. On dequeueing an element, we return the value pointed to by FRONT and increase the FRONT
index.

5. Before enqueing, we check if queue is already full.

6. Before dequeuing, we check if queue is already empty.

7. When enqueing the first element, we set the value of FRONT to 1.

8. When dequeing the last element, we reset the values of FRONT and REAR to 0.

Representation of Queue (or) Implementation of Queue:

The queue can be represented in two ways:

1. Array implementation of queue(static memory allocation)

2. Linked list implementation of queue(dynamic memory allocation)

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 108


1. Queue using Array

One of the most common way to implement a queue is using array. An easy way to do so is to define
an array Queue, and two additional variables front and rear.

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 109


Deleting an Element from the Queue :

Elements are always removed from the front. After removing the element, front is incremented by
one. Fig. 11.1 f shows status of front and rear after two deletions from Fig. 11.1d. Observe that
positions vacated by front marked as * are unusable by queue any further.

This is one of the major draw back of linear queue array representation. In Fig. 11.1 g, we have
carried out three deletions for 25,35,and 45. after deleting 45, we find queue is empty and the
condition for this queue state is q.rear is less than q.front. At this stage, we can reinitialize the queue
by setting q.front=0 and q.rear = -1 and thus reclaim the unused positions marked with *.

Queue operations using array:

a) enqueue() or insertion():which inserts an element at the end of the queue.

void insertion() {

if(rear==max-1)

cout<<"\n Queue is Full";

else {

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 110


cout<<"\n Enter no “;

cin>>queue[rear++];

b)dequeue() or deletion(): which deletes an element at the start of the queue.

void deletion() {

if(front>rear-1) {

cout<<"\n Queue is empty";

else

Cout<<"\n Deleted Element is "<<queue[front++];

x++;

b) dispaly(): which displays an elements in the queue


void deletion() {
if(front>rear-1)
{
Cout<<"\n Queue is empty";
}
else
{
for(i=front; i<rear;i++)
cout<<queue[i])<<endl;
}
}

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 111


Array implementation of a Queue do have drawbacks.
• The maximum queue size has to be set at compile time, rather than at run time.
• Space can be wasted, if we do not use the full capacity of the array

DATA STRUCTURES AND ALGORITHMS-MR ARAKA 112

You might also like