0% found this document useful (0 votes)
26 views74 pages

UNIT - 1:: Data Structures

Uploaded by

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

UNIT - 1:: Data Structures

Uploaded by

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

UNIT - 1:

Data Structures:

A data structure is a storage that is used to store and organize data. It is a


way of arranging data on a computer so that it can be accessed and updated
efficiently.
A data structure is not only used for organizing the data. It is also used for
processing, retrieving, and storing data.
The data structure is not any programming language like C, C++, java, etc.
It is a set of algorithms that we can use in any programming language to
structure the data in the memory.

Classification of Data Structure:

Non
Primitive Data Structures:

Primitive data structure is a fundamental type of data structure that stores


the data of only one type. It is a data structure that can hold a single value in a
specific location.

These data structures can be manipulated or operated directly by machine-level


instructions.

Integer (4 bytes) - The integer data type contains the numeric values. It
contains the whole numbers that can be either negative or positive. Ex:
10, 97, -41
Float (4 bytes) - The float is a data type that can hold decimal values upto 6
digits.
Ex: 3.127461
Character(1 byte) - It is a data type that can hold a single character value
both uppercase and lowercase such as 'A' or 'a'.
Boolean(1 bit) - It is a data type that can hold either a True or a False value.
Ex: 1 or 0 (True or False).

Non-primitive Data Structures:

Non-primitive data structures are complex data structures that are derived
from primitive data structures. It can hold multiple values either in a contiguous
location or random locations.

The non-primitive data types are defined by the programmer. The non-primitive
data structure is further classified into two categories.

Linear Data Structures


Non-Linear Data Structures
Linear Data Structures:

Linear Data Structure consists of data elements arranged in a sequential


manner where every element is connected to its previous and next elements.

The following are the types of linear data structure

Array:

An array is a collection of similar data elements. These data elements have


the same data type. The elements of the array are stores in consecutive memory
locations and are referenced by an index.

Syntax: data_type array_name[size];

Example: int marks[10];

Memory representation of an array of 10 elements

Linked List:

A linked list is a linear data structures that is used to maintain a list-


like structure in the computer memory. It is a group of nodes that are not stored at
contiguous locations. Each node of the list is linked to its adjacent node with the
help of pointers.

Simple Linked List


Stack:
Stack is a linear data structure that follows a particular order in which the
operations are performed. The order is LIFO (Last in first out). Entering
and retrieving data is possible from only one end.

It contains two operations – push, pop

Queue:

Queue is a linear data structure in which elements can be inserted from


only one end which is known as rear and deleted from another end known as front.
It follows the FIFO (First In First Out) order. It contains two operations –
enqueue, dequeue
Non-Linear Data Structures:
Non-linear Data Structures do not have any set
sequence of connecting all its elements and every element can have multiple paths
to attach to other elements.

Trees:

A tree is a multilevel data structure defined as a set of nodes. The topmost


node is named root node while the bottom most nodes are called leaf nodes.
Each node has only one parent but can have multiple children.

Trees

Graph:

A graph is a nonlinear data structure and a graph is a set of vertexes and


edges. Each vertex connected with path; each path is called edges. A graph is a
pictorial representation of a set of objects connected by links known as edges. The
interconnected nodes are represented by points named vertices, and the links that
connect the vertices are called edges.
Data Structures Operations:

The common operations that can be performed on the data structures are as
follows

Traversing: Traversing a Data Structure means to visit the element stored in it. It
visits data in a systematic manner.

Searching: Searching means to find a particular element in the given data-


structure. It is considered as successful when the required element is found.

Sorting: Sorting means to arrange the data elements in either Ascending or


Descending order.

Create: Create is an operation used to reserve memory for the data elements of the
program. We can perform this operation using a declaration statement. The
creation of data structure can take place either during the following:
1. Compile-time
2. Run-time

Insertion:

Insertion means inserting or adding new data elements to the collection.


The operation of insertion is successful when the required element is added to
the required data-structure.

Deletion:

Deletion means to remove or delete a specific data element from the


given list of data elements. The operation of deletion is successful when the
required element is deleted from the data structure.

Merge:

Merge means to combine data elements of two sorted lists in order to form
a single list of sorted data elements.
Splitting:

The Splitting operation allows us to divide data into various subparts decreasing
the overall process completion time.
Arrays:

Introduction:
An array is a data structure that sequentially stores an element of the same
data type.
In C/C++ or any other programming language, an array is a collection of
similar data items.
The data items are always stored in an array at contiguous memory
locations.
It is a data structure where we store similar elements.
We can store only a fixed set of elements in array.

Storing Values in array:

When we declare an array, we are just allocating space for its elements; no
values are stored in the array. There are three ways to store values in an array.
Initializing Arrays during Declaration:

The elements of an array can be initialized at the time of declaration, just as


any other variable. When an array is initialized, we need to provide a value for
every element in the array.

Syntax: data_type array_name[size]={list of values};

Example: int marks[5]={ 90 , 45, 67, 85, 78};

int marks[5] ={90, 45};

Inputting Values from the Keyboard:


An array can be initialized by inputting
values from the keyboard at the time of runtime. In this method, a while/do–while
or a for loop and scanf function is executed to input the value for each element of
the array.

Example: int i, marks[10];

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

scanf(“%d”, &marks[i]);

Assigning Values to Individual Elements:


The third way is to assign values to
individual elements of the array by using the assignment operator. Any value that
evaluates to the data type as that of the array can be assigned to the individual
array element.

Example: marks[3] = 100;


Operations on arrays:
There are a number of operations that can be performed
on arrays. These operations include:

Traversing an Array:
Traversing an array means accessing each and every
element of the array for a specific purpose. It prints all array elements one after
another.
Inserting an element:
Inserting operation is performed to insert one or more
elements into the array. As per the requirements, an element can be added at the
beginning, end, or at any index of the array.
Deleting an element:
Deleting an element from an array means removing a data
element from an already existing array and then reorganizes all of the array
elements.
Search operation:
Search operation is performed to search an element in the array
based on the value or index.
Sort operation:
Sort operation helps to arrange the data elements in either
Ascending or Descending order.

Merging two arrays:


Merging two arrays in a third array means first copying the
contents of the first array into the third array and then copying the contents of the
second array into the third array.
Types of array.

1. Single Dimensional Array


2. Two-Dimensional Array
3. Multidimensional Array

Single Dimensional Array:

A single dimension array holds various elements of the same data type.
To identify and find the value of a particular component, we use the array
name and the value of an index element.
Array in C, is always used with only one subscript ( []).
A one-dimensional array behaves likes a list of variables.

data_type array_name [array_size];

Example:
int marks [100];
int myNumbers[4];
myNumbers[0]= 10;
myNumbers[1]= 20;
myNumbers[2]= 30;
myNumbers[3]= 40;
Example:

#include <stdio.h>
int main()
{
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
for(int i=0; i<5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}

Output:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Two-Dimensional Array in C:

The two-dimensional array can be defined as an array of arrays.


The 2D array is organized as matrices which can be represented as the
collection of rows and columns.
2D arrays are created to implement a relational database lookalike data
structure.
It provides ease of holding the bulk of data at once which can be passed to
any number of functions wherever required.

Syntax:

data_type array_name[rows][columns];

int twodimen[4][3];
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example:
#include<stdio.h>
int main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output:
arr [0][0] = 1
arr [0][1] = 2
arr [0][2] = 3

arr [1][0] = 2
arr [1][1] = 3
arr [1][2] = 4

arr [2][0] = 3
arr [2][1] = 4
arr [2][2] = 5

arr [3][0] = 4
arr [3][1] = 5
arr [3][2] = 6
Mmulti-dimensional array:
A multi-dimensional array is an array with more than
one level or dimension. For example, a 2D array, or two-dimensional array, is an
array of arrays, meaning it is a matrix of rows and columns (think of a table).

int arr[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Example:
#include <stdio.h>
void arr(int x[][3]); //function prototype
int main ()
{
int a[2][3] = {{1,2,3}, {4,5,6}}; //initializing array
int b[2][3] = {1, 2, 3, 4, 5};
int c[2][3] = {{1, 2}, {4}};
printf("values in array a by row:\n");
arr(a);
printf("values in array b by row:\n");
arr(b);
printf("values in array c by row:\n");
arr(c);
return 0;
} // end of main
void arr(int x[][3])
{
int i; //row counter
int j; //column counter
for (i = 0; i <= 1; ++i)
{
for (j = 0; j<= 2; ++j)
{
printf("%d", x[i][j]);
} //end of inner for
printf("\n");
} //end of outer for
}
Output:
values in array a by row:
1 2 3
4 5 6
values in array b by row:
1 2 3
4 5 0
values in array c by row:
1 2 0
4 0 0
Insertion:

#include <stdio.h>
main()
{
int Arr[] = {1,3,5,7,8};
int insert = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
n = n + 1;
while( j >= k)
{
Arr[j+1] = Arr[j];
j = j - 1;
}
Arr[k] = insert;
printf("The array elements after insertion:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
Output:
The original array elements are:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 5
Arr[3] = 7
Arr[4] = 8
The array elements after insertion:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 5
Arr[3] = 10
Arr[4] = 7
Arr[5] = 8
Deletion Array Operations:

Deletion is the process of eliminating an existing element from an array and


rearranging all of the array’s elements.

Algorithm:
Take into consideration that K is a positive integer such that K=N and Arr is a
linear array with N items. The algorithm to remove one element from the Kth
position of Arr is shown below.

Step: 1 Start

Step: 2 Set J = K

Step: 3 Repeat steps 4 and 5 while J < N

Step: 4 Set Arr[J] = Arr[J + 1]

Step: 5 Set J = J+1

Step: 6 Set N = N-1

Step: 7 Stop
Example:

#include <stdio.h>
void main()
{
int Arr[] = {1,3,5,7,8};
int del = 3, n = 5;
int i, j;
printf("The original array elements are:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
j = del;
while( j < n)
{
Arr[j-1] = Arr[j];
j = j + 1;
}
n = n -1;
printf("The array elements after deletion:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
Output:
The original array elements are:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 5
Arr[3] = 7
Arr[4] = 8
The array elements after deletion:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 7
Arr[3] = 8
Search Array Operations:

An array element can be found using either its value or its index.

Algorithm:
Take into consideration that K is a positive integer such that K=N and
Arr is a linear array with N items. The sequential search technique to locate an
element with the value of ITEM is shown below.

Step: 1 Start

Step: 2 Set J = 0

Step: 3 Repeat steps 4 and 5 while J < N

Step: 4 IF Arr[J] is equal ITEM THEN GOTO STEP 6

Step: 5 Set J = J +1

Step: 6 PRINT J, ITEM

Step: 7 Stop
Example:

#include <stdio.h>
void main()
{
int Arr[] = {1,3,5,7,8};
int search = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
while( j < n)
{
if( Arr[j] == search)
{
break;
}
j = j + 1;
}
printf("Found element %d at position %d\n", search, j+1);
}
}
Output:
The original array elements are:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 5
Arr[3] = 7
Arr[4] = 8
Found element 5 at position 3
Update Array Operations

Update array operations involve changing an existing array element at a certain


index.

Algorithm
Take into consideration that K is a positive integer such that K=N and Arr is a linear
array with N items. The technique to update an element that is accessible at the Kth
position of Arr is shown below.

Step: 1 Start

Step: 2 Set Arr[K-1] = ITEM

Step: 3 Stop

Example:
#include <stdio.h>
void main()
{
int Arr[] = {1,3,5,7,8};
int m = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
Arr[m-1] = item;
printf("The array elements after updation:\n");
for(i = 0; i<n; i++)
{
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
Output:
The original array elements are:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 5
Arr[3] = 7
Arr[4] = 8
The array elements after updation:
Arr[0] = 1
Arr[1] = 3
Arr[2] = 10
Arr[3] = 7
Arr[4] = 8
Write A Program To Print All The Elements Of Array In Reverse Order.
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr)/sizeof(arr[0]);
printf("Original array: \n");
for (int i = 0; i < length; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
printf("Array in reverse order: \n");
for (int i = length-1; i >= 0; i--)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Original array:
12345
Array in reverse order:
54321
Stacks:

Stacks is a linear data structure, that follows the LIFO (Last-In-First-


Out) principle and allows insertion and deletion operations from one end, we can
insert and delete the elements from the same end and from top of the Stack.

The stack can perform the two types of operations Push and Pop
Inserting the elements into the stack is called Push and Deletion of the
elements from the Stack is called Pop
in which insertion and deletion can be done from the one end known as the
top of the stack.
Initially top the stack is, top = -1.
Stack Operations:

The following are some common operations implemented on the stack:

push (): When we insert an element in a stack then the operation is known
as a push. If the stack is full then the overflow condition occurs.
pop(): When we delete an element from the stack, the operation is known as
a pop. If the stack is empty means that no element exists in the stack, this
state is known as an underflow state.
isEmpty(): It determines whether the stack is empty or not.
isFull(): It determines whether the stack is full or not.'
peek(): It returns the element at the given position.
count(): It returns the total number of elements available in a stack.
change(): It changes the element at the given position.
display(): It prints all the elements available in the stack.

PUSH operation:

The steps involved in the PUSH operation is given below:

Before inserting an element in a stack, we check whether the stack is full.


If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
When we initialize a stack, we set the value of top as -1 to check that the
stack is empty.
When the new element is pushed in a stack, first, the value of the top gets
incremented, i.e., top=top+1, and the element will be placed at the new
position of the top.
The elements will be inserted until we reach the max size of the stack.
POP operation:

The steps involved in the POP operation is given below:

Before deleting the element from the stack, we check whether the stack is
empty.
If we try to delete the element from the empty stack, then
the underflow condition occurs.
If the stack is not empty, we first access the element which is pointed by
the top
Once the pop operation is performed, the top is decremented by 1,
i.e., top=top-1.
Example:

#include <stdio.h>
int MAXSIZE = 10;
int stack[10];
int top = -1;
int isempty() /* check if the stack is empty */
{
if(top == -1)
return 1;
else
return 0;
} 1

int isfull() /* Check if the stack is full */


{
50
if(top == MAXSIZE)
40
return 1; 30
else 20
10
return 0;
} 1
/* Function to return the topmost element in the stack */
int peek() 50
Peep
element 40

{ 30
20
return stack[top];
} 10
int pop() /* Function to delete from the stack */
{
int data;
if(!isempty())
{
data = stack[top];
top = top - 1;
return data;
}
else
{
printf("Could not retrieve data, Stack is empty.\n");
}
}
int push(int data) /* Function to insert into the stack */
{
if(!isfull())
{
top = top + 1;
stack[top] = data;
}
else
{
printf("Could not insert data, Stack is full.\n");
}
}
int main() /* Main function */
{
push(10);
push(20);
push(30);
push(40);
push(50);
printf("Element at top of the stack: %d\n" ,peek());
printf("Elements: \n");
// print stack data
while(!isempty())
{
int data = pop();
printf("%d\n", data);
}
printf("Stack full: %s\n" , isfull()?"true": "false");
printf("Stack empty: %s\n" , isempty()?"true": "false");
return 0;
}
Output:
Element at top of the stack: 50
Elements:
50
40
30
20
10
Stack full: False
Stack empty: true
Queues:
What is a queue in C?
A queue in C is basically a linear data structure to store and
manipulate the data elements. It follows the order of First In First Out (FIFO). In
queues, the first element entered into the array is the first element to be removed
from the array.

1) Simple Queue or Linear Queue


2) Circular Queue
3) Priority Queue
4) Double Ended Queue (or Deque)
Simple Queue:

Simple Queue is also called as Linear Queue, an insertion takes


place from one end and deletion occurs from another end. The end at which the
insertion takes place is known as the rear end, and the end at which the deletion
takes place is known as front end. It strictly follows the FIFO rule.

Algorithm:
Enqueue:
 Step 1: IF REAR = MAX-1
PRINT “OVERFLOW”
Goto step 4
[END OF IF]
 Step 2: IF FRONT=-1 and REAR=-1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR+1
[END OF IF]
 Step 3: SET QUEUE[REAR] = VAL
 Step 4: EXIT
Dequeue:
 Step 1: IF FRONT = -1
PRINT “UNDERFLOW”
[END OF IF]
 Step 2:
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT+1
IF FRONT > REAR
FRONT = REAR = -1
[END OF IF]
 Step 3: EXIT
Example:
#include<stdio.h>
#define MAX 5
int front = -1;
int rear = -1;
int queue[];
void enqueue(int queue[], int val)
{
if(rear == MAX -1)
printf("\n OVERFLOW");
if(front == -1 && rear == -1)
front = rear = 0;
else
rear++;
queue[rear] = val;
}
int dequeue (int queue[])
{
if(front == -1 || front > rear)
{
printf("\n UNDERFLOW");
return -1;
}
else
{
int val = queue[front];
front++;
return val;
}
}
void display(int queue[])
{
if(front == -1 && rear == -1)
printf("|n Queue is empty!");
else
{
int i;
printf("\n");
for(i = front; i <rear; i++)
printf("\t %d", queue[i]);
}
}
int main()
{
int option, val;
do
{
printf("\n ***** Enter Your Choice *****");
printf("\n 1. Insert an element");
printf("\n 2. Delete an element");
printf("\n 3. display the queue");
printf("\n 4. EXIT");
printf("\n **********************");
printf("\n\n ENTER your option: ");
scanf("%d", &option);
switch(option)
{
case 1:
printf("\n Enter the element to the queue: ");
scanf("%d", &val);
enqueue(queue, val );
break;
case 2:
val = dequeue(queue);
if (val != -1)
printf("\n The number deleted is : %d", val);
break;
case 3:
display(queue);
break;
}
}
while(option!= 4);
}
Output:
***** Enter Your Choice *****
1. Insert an element
2. Delete an element
3. display the queue
4. EXIT
**********************
ENTER your option: 1
Enter the element to the queue: 10
Circular Queue:

In Circular Queue, all the nodes are represented as circular. It is


similar to the linear Queue except that the last element of the queue is connected
to the first element. It is also known as Ring Buffer, as all the ends are connected
to another end.

Front: It is used to get the front element from the Queue.


Rear: It is used to get the rear element from the Queue.
enQueue (value): This function is used to insert the new value in the
Queue. The new element is always inserted from the rear end.
deQueue (): This function deletes an element from the Queue. The deletion
in a Queue always takes place from the front end.
Algorithm to insert an element in a circular queue:

Step 1: IF (REAR+1) %MAX = FRONT


Write " OVERFLOW "
Goto step 4
[End OF IF]

Step 2: IF FRONT = -1 and REAR = -1


SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT
Algorithm to delete an element from the circular queue

Step 1:

IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]

Step 2:

SET VAL = QUEUE[FRONT]

Step 3:

IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]

Step 4: EXIT
Example:
#include<stdio.h>
#include<stdlib.h>
# define N 5 //N = Maximum Size of the Q
int cq [N]; //cq = Circular Queue
int front=-1;
int rear=-1;
void enqueue (int item);
int dequeue ();
int isEmpty ();
int isFull ();
void enqueue(int item)
{
if(isFull ())
{
printf("Queue Overflow: \n");
exit(1);
}
if(front == -1)
{
front=0;
}
rear=(rear+1) % N; // rear is incremented
cq[rear]=item; // assigning a value to the queue at the rear position.
}
int dequeue()
{
int deleted_item;
if(isEmpty ())
{
printf("Queue Underflow: \n");
exit(1); // To show Failure Exit.
}
deleted_item = cq [front];
if(front==rear) // cq has only 1 element
{
front=-1;
rear=-1;
}
else
{
front = (front + 1) %N;
}
return deleted_item;
}
int isEmpty ()
{
return ( (front == -1) ? 1 : 0);
}
int isFull()
{
return ( ( (rear + 1)%N == front) ? 1 : 0);
}
void display()
{
int i;
if(isEmpty ())
{
printf("Queue Underflow: \n.");
return;
}
i = front;
if (front < rear)
{
while(i<=rear)
{
printf("%d,", cq[i]);
i=i+1;
}
}
else
{
while(i != rear)
{
printf("%d", cq[i]);
i=(i+1)%N;
}
printf("%d,", cq[i]);
}
}
int main()
{
enqueue (11); // Insert elements: 11,22,33,44,55
enqueue (22);
enqueue (33);
enqueue (44);
enqueue (55);
display ();
printf("\n Deleted Element is: %d\n", dequeue()); // Delete first elements
printf("\n Deleted Element is: %d\n", dequeue()); // Delete Second elements
enqueue (66); // Insert 66
display ();
return 0;
}

Output:
11, 22, 33, 44, 55
Deleted Element is: 11
Deleted Element is: 22
33, 44, 55, 66,
Priority Queue:

It is a special type of queue in which all the elements are arranged based on
the priority and every element has a priority associated with it.
Suppose some elements occur with the same priority, they will be arranged
according to the FIFO principle.
An ascending order priority queue gives the highest priority to the lower
number in that queue.

There are two types of priority queue:

Ascending priority queue - In ascending priority queue, elements can be


inserted in arbitrary order, but only smallest can be deleted first. Suppose an
array with elements 7, 5, and 3 in the same order, so, insertion can be done
with the same sequence, but the order of deleting the elements is 3, 5, 7.
Descending priority queue - In descending priority queue, elements can be
inserted in arbitrary order, but only the largest element can be deleted first.
Suppose an array with elements 7, 3, and 5 in the same order, so, insertion
can be done with the same sequence, but the order of deleting the elements
is 7, 5, 3.
Example:

#include<stdio.h>
#include<limits.h>
#define MAX 100
int idx = -1;
int pqVal[MAX];
int pqPriority[MAX];
int isEmpty()
{
return idx == -1;
}
int isFull()
{
return idx == MAX - 1;
}
void enqueue(int data, int priority)
{
if(!isFull())
{
idx++;
pqVal[idx] = data;
pqPriority[idx] = priority;
}
}
int peek()
{
int maxPriority = INT_MIN;
int indexPos = -1;
for (int i = 0; i <= idx; i++)
{
if (maxPriority == pqPriority[i] && indexPos > -1 && pqVal[indexPos] < pqVal[i])
{
maxPriority = pqPriority[i];
indexPos = i;
}
else if (maxPriority < pqPriority[i])
{
maxPriority = pqPriority[i];
indexPos = i;
}
}
return indexPos;
}

void dequeue()
{
if(!isEmpty())
{
int indexPos = peek();
for (int i = indexPos; i < idx; i++)
{
pqVal[i] = pqVal[i + 1];
pqPriority[i] = pqPriority[i + 1];
}
idx--;
}
}

void display()
{
for (int i = 0; i <= idx; i++)
{
printf("(%d, %d)\n",pqVal[i], pqPriority[i]);
}
}
int main()
{
enqueue(5, 1);
enqueue(10, 3);
enqueue(15, 4);
enqueue(20, 5);
enqueue(25, 2);
printf("Priority Queue Before Dequeue : \n");
display();
dequeue();
dequeue();
dequeue();
printf("\nPriority Queue After Dequeue : \n");
display();
return 0;
}
Output:

Priority Queue Before Dequeue:

(5, 1)

(10, 3)

(15, 4)

(20, 5)

(25, 2)

Priority Queue After Dequeue:

(5, 1)
(25, 2)
Deque (Double Ended Queue):

In Deque or Double Ended Queue, insertion and deletion can be done from
both ends of the queue either from the front or rear.
It means that we can insert and delete elements from both front and rear
ends of the queue.
Deque can be used as a palindrome checker means that if we read the string
from both ends, then the string would be the same.

Operations:

Enqueue:
The Enqueue operation is used to insert the element at the rear
end of the queue. It returns void.

Dequeue:
It performs the deletion from the front-end of the queue. It also
returns the element which has been removed from the front-end. It returns
an integer value.

Peek:
This is the third operation that returns the element, which is pointed by
the front pointer in the queue but does not delete it.
Queue overflow (isfull):
It shows the overflow condition when the queue is
completely full.

Queue underflow (isempty):


It shows the underflow condition when the
Queue is empty, i.e., no elements are in the Queue.
implement of queue:

There are two ways of implementing the Queue:

Implementation using array:

The sequential allocation in a Queue can be implemented using an array.

Implementation using Linked list:


The linked list allocation in a Queue can be implemented using a linked list.
Types of DE Queues:
1.Input Restricted DE Queue: in this Dequeue input is restricted at a single end
but it allows deletion at both ends.
2.Output Restricted DE Queue: in this Dequeue output is restricted at a single
end but it allows insertion at both ends.
Operations on DE Queue:

Operations performed on deque:

There are the following operations that can be applied on a deque -

1. Insertion at Begin / Insertion at front


2. Insertion at End / Insertion at rear
3. Deletion at Begin / Deletion at front
4. Deletion at End / Deletion at rear
Insertion at Begin / Insertion at front:

Explanation:
int dq[4];
int front =-1;
int rear = - 1;
int c = 5;

if(front = =0 && rear= =3) 1 2 3 4

{ 0 1 2 3
printf(“ DE queue is full”); Front Rear
}
if(front = = 0) 1 2
{ 0 1 2 3
printf(“insertion not possible”); Front Rear
}
else Front
{
front= front-1; 1 2
dq[front]=c; 0 1 2 3
Front Rear
Insertion at End / Insertion at front:

Explanation:

int dq[10];
int front =-1;
int rear = - 1;
int c = 5;

if(front = =0 && rear= =3) 1 2 3 4

{ 0 1 2 3
printf(“ DE queue is full”); Front Rear
}
if(front = = 3) 1 2
{ 0 1 2 3
printf(“insertion not possible”); Front Rear
}
else
{
Rear = Rear + 1; 1 2 3 1 2 3 5
dq[rear]=c; 0 1 2 3 0 1 2 3
Front Rear Front Rear
deletion at Begin / Insertion at Rear:

Explanation:

int dq[4];
int front =-1;
int rear = - 1;
int c = 5;

if(front = =0 && rear= =3)


{ 0 1 2 3
printf(“ DE queue is Empty”);
}
printf(“delete the element”,dq[front]);
if(front = = rear) 1
{ 0 1 2 3
Front=rear = -1; Front Rear
}
else
{
front = front + 1; 1 2 3 2 3

} 0 1 2 3 0 1 2 3
Front Rear Front Rear
deletion at End / Insertion at Front:

Explanation:

int dq[5];
int front =-1;
int rear = - 1;
int c = 5;

if(front = =0 && rear= =3)


{ 0 1 2 3
printf(“ DE queue is Empty”);
}
printf(“delete the element”,dq[front]);
if(front = = rear) 1
{ 0 1 2 3
front=rear = -1; Front Rear
}
else
{
rear = rear - 1; 1 2 3 1 2

} 0 1 2 3 0 1 2 3
Front Rear Front Rear
Example:
#include <stdio.h>
#define MAX 10
void addFront (int *, int, int *, int *);
void addRear (int *, int, int *, int *);
int delFront (int *, int *, int *);
int delRear (int *, int *, int *);
void display (int *);
int count(int *);
int main()
{
int arr[MAX];
int front, rear, i, n;
front = rear = -1;
for (i = 0; i < MAX; i++)
arr[i] = 0;
addRear( arr, 10, &front, &rear);
addFront (arr, 20, &front, &rear);
addRear (arr, 30, &front, &rear);
addFront (arr, 40, &front, &rear); // insert element //
addRear (arr, 50, &front, &rear);
addFront (arr, 60, &front, &rear);
printf("\n Elements in a deque: ");
display(arr); // display the list of elements
i = delFront (arr, &front, &rear);
printf("\n removed item: %d", i);
printf("\n Elements in a deque after deletion: ");
display(arr);
addRear (arr, 100, &front, &rear);
addRear (arr, 200, &front, &rear);
printf("\n Elements in a deque after addition: ");
display(arr);
i = delRear (arr, &front, &rear);
printf("\n removed item: %d", i);
printf("\n Elements in a deque after deletion: ");
display(arr);
n = count(arr); // count number elements //
printf("\n Total number of elements in deque: %d", n);
}
void addFront(int *arr, int item, int *pfront, int *prear)
{
int i, k, c;
if (*pfront == 0 && *prear == MAX - 1)
{
printf("\n Deque is full.\n");
return;
}
if (*pfront == -1)
{
*pfront = *prear = 0;
arr[*pfront] = item;
return;
}
if (*prear != MAX - 1)
{
c = count(arr);
k = *prear + 1;
for (i = 1; i <= c; i++)
{
arr[k] = arr[k - 1];
k--;
}
arr[k] = item;
*pfront = k;
(*prear) ++;
}
else
{
(*pfront) --;
arr[*pfront] = item;
}
}
void addRear(int *arr, int item, int *pfront, int *prear)
{
int i, k;
if (*pfront == 0 && *prear == MAX - 1)
{
printf("\n Deque is full.\n");
return;
}
if (*pfront == -1)
{
*prear = *pfront = 0;
arr[*prear] = item;
return;
}
if (*prear == MAX - 1)
{
k = *pfront - 1;
for (i = *pfront - 1; i < *prear; i++)
{
k = i;
if (k == MAX - 1)
arr[k] = 0;
else
arr[k] = arr[i + 1];
}
(*prear) --;
(*pfront) --;
}
(*prear) ++;
arr[*prear] = item;
}
int delFront(int *arr, int *pfront, int *prear)
{
int item;
if (*pfront == -1)
{
printf("\n Deque is empty.\n");
return 0;
}
item = arr[*pfront];
arr[*pfront] = 0;
if (*pfront == *prear)
*pfront = *prear = -1;
else
(*pfront)++;
return item;
}
int delRear (int *arr, int *pfront, int *prear)
{
int item;
if (*pfront == -1)
{
printf("\n Deque is empty.\n");
return 0;
}
item = arr[*prear];
arr[*prear] = 0;
(*prear)--;
if (*prear == -1)
*pfront = -1;
return item;
}
void display(int *arr)
{
int i;
printf("\n front: ");
for (i = 0; i < MAX; i++)
printf(" %d", arr[i]);
printf(" :rear");
}
int count (int *arr)
{
int c = 0, i;
for (i = 0; i < MAX; i++)
{
if (arr[i] != 0)
c++;
}
return c;
}
Output:
Elements in a deque:
front: 60 40 20 10 30 50 0 0 0 0 :rear
removed item: 60
Elements in a deque after deletion:
front: 0 40 20 10 30 50 0 0 0 0 :rear
Elements in a deque after addition:
front: 0 40 20 10 30 50 100 200 0 0 :rear
removed item: 200
Elements in a deque after deletion:
front: 0 40 20 10 30 50 100 0 0 0 :rear
Total number of elements in deque: 6
Algorithm for Insertion at rear end

Step -1: [Check for overflow]

if(rear = =MAX)

Print("Queue is Overflow”);

return;

Step-2: [Insert element]

else

rear=rear+1;

q[rear]=no;

[Set rear and front pointer]

if rear=0

rear=1;

if front=0

front=1;

Step-3: return
Implementation of Insertion at rear end

void add_item_rear()

int num;

printf("\n Enter Item to insert : ");

scanf("%d", &num);

if(rear==MAX)

printf("\n Queue is Overflow");

return;

else

rear++;

q[rear]=num;

if(rear = =0)

rear =1;

if(front ==0)

front=1;

}
Algorithm for Insertion at front end:

Step-1: [Check for the front position]

if(front<=1)

Print (“Cannot add item at front end”);

return;

Step-2: [Insert at front]

else

front=front-1;

q[front]=no;

Step-3: Return
Implementation of Insertion at front end:

void add_item_front()

int num;

printf(" \n Enter item to insert: ");

scanf("%d", &num);

if(front<=1)

printf(" \n Cannot add item at front end ");

return;

else

front--;

q[front]=num;

}
Algorithm for Deletion from rear end:

Step-1: [Check for the rear pointer]

if rear=0

print(“Cannot delete value at rear end”);

return;

Step-2: [ perform deletion]

else

no=q[rear];

[Check for the front and rear pointer]

if front= rear

front=0;

rear=0;

else

rear=rear-1;

print(“Deleted element is”, no);

Step-3: Return
Implementation of Deletion from rear end
void delete_item_rear()

int num;

if(rear ==0)

printf(" \n Cannot delete item at rear end\n");

return;

else

num=q[rear];

if(front==rear)

front=0;

rear=0;

else

rear--;

printf("\n Deleted item is %d\n", num);

}
}
}
Algorithm for Deletion from front end:

Step-1: [ Check for front pointer]

if front=0

print(" Queue is Underflow”);

return;

Step-2: [Perform deletion]

else

no=q[front];

print(“Deleted element is”, no);

[Set front and rear pointer]

if front=rear

front=0;

rear=0;

else

front=front+1;

Step-3: Return
Implementation of Deletion from front end:
void delete_item_front()

int num;

if(front==0)

printf(" \n Queue is Underflow\n ");

return;

else

num=q[front];

printf(" \n Deleted item is %d\n ", num);

if(front==rear)

front=0;

rear=0;

else

front++;

You might also like