You are on page 1of 35

1.

Introduction to Data structures


 Data Structures is the concept of set of algorithms used to structure the information.
 In computer terms, a data structure is a Specific way to store and organize data in a computer's memory so that
these data can be used efficiently later.
 Data may be arranged in many ways such as the logical or mathematical model for a particular organization of data is
termed as a data structure.

2. To store and process data we may use the following operations.


 The different operations used on data structure are:
1) Create: we reserve memory for program elements: This can be done by using malloc or calloc function. We can
create a data structure with giving different elements.
2) Insert: we reserve memory for program element. This can be done by using malloc or calloc function. We can
insert an element into a data structure.
3) Delete: It delete memory space allocated for specified data structure using free ().
4) Display: It deals with accessing a particular data within a data structure.
5) Searching: It finds the data item in the list of data items. It’s also find the location of all elements.
6) Sorting: It is the process of arranging all data items in a data structure in a particular order say either in
ascending order or in descending order.
7) Merging: It is the process of combining the data items of two different sorted list into a single sorted list.
8) Splitting: It is the process of partitioning single list to multiple lists.
9) Traversal: It is the process of visiting each and every node of a list in systematic manner.

3. Classification of Data Structures:


 Data structures are normally classified into two types.
1) Primitive data structures: Primitive data structures are built in types in most programming languages. They are.
a. Integer: It is whole numbers. i.e., negative values, 0, positive values
b. Float: It is fractional numbers
c. Character: It is character values
d. Boolean: it represents true or false.
2) Non-primitive data structures: These are derived from primitive data structures.
a. They are Array, Structure, Union, Files etc.
b. A Non-primitive data type is further divided into Linear and Non-Linear data structure.

4. Categories of Non-Primitive Data Structure:


 Non-Primitive Data structures are classified into two types.
1) Linear Data Structure
2) Non-linear Data Structure
5. Linear Data Structure:
 A data structure is said to be linear if its elements combine to form any specific order.
 There are basically two techniques of representing such linear structure within memory.
 First way is to provide the linear relationships among all the elements represented by means of linear memory
location. These linear structures are termed as arrays.
 The second technique is to provide the linear relationship among all the elements represented by using the concept
of pointers or links. These linear structures are termed as linked lists.
 The common examples of linear data structure are:
1) Arrays
2) Queues
3) Stacks
4) Linked lists

6. Non-linear Data Structure:


 This structure is mostly used for representing data that contains a hierarchical relationship among various elements.
 Examples of Non-Linear Data Structures are listed below:
1) Graphs
2) family of trees and
3) table of contents

7. Differences between Linear and Non-Linear Data Structures:


Linear Data Structure Non-Linear Data Structure
Every data element is connected to its previous & next one Every data element relates to many other data elements.
Data is arranged in a sequence manner Data is not arranged in a sequence manner
Data can be traversed in a single run Data cannot be traversed in a single run
Ex: Array, Stack, Queue, Linked List Ex: Tree, Graph
Implementation is easy Implementation is difficult
8. Link List
 A linked list is a collection of data elements called nodes in which the linear representation is given by links from one
node to the next node.
 A linked list does not store its elements in consecutive memory locations and the user can add any number of
elements to it.
 The elements in a linked list can be accessed only in a sequential manner. But like an array, insertions and deletions
can be done at any point in the list in a constant time.
 A linked list, in simple terms, is a linear collection of data elements. These data elements are called nodes. Linked list
is a data structure which in turn can be used to implement other data structures.
 Thus, it acts as a building block to implement data structures such as stacks, queues, and their variations.

 Following are the important terms to understand the concept of Linked List.
 Link − Each link of a linked list can store a data called an element.
 Next − Each link of a linked list contains a link to the next link called Next.
 LinkedList − A Linked List contains the connection link to the first link called First.

Basic Terminology:
 A linked list can be perceived as a sequence of nodes in which each node contains one or more data fields and a
pointer to the next node.
 We can see a linked list in which every node contains two parts, an integer, and a pointer to the next node.
 The last node will have no next node connected to it, so it will store a special value called NULL.
 Since in a linked list, every node contains a pointer to another node which is of the same type, it is also called a self-
referential data type.

Linked Lists versus Arrays:


Both arrays and linked lists are a linear collection of data elements. But unlike an array, a linked list does not store
its nodes in consecutive memory locations. Another point of difference between an array and a linked list is that a
linked list does not allow random access of data. Nodes in a linked list can be accessed only in a sequential manner.
Another advantage of a linked list over an array is that we can add any number of elements in the list. This is not
possible in case of an array.

9. What is a Linked List?


 A linked list is a sequence of data structures. It is also known as a linear data structure that comprises a set of
connected nodes. Each node is used to store the data and the address of the next node.

 The starting point of the linked list is known as the head of the list. It is not a different node, but refers to the first node.
 The node present in the end is called NULL.

Types of Linked List


There are 3 different types of Linked Lists:

1. Singly Linked List


2. Doubly Linked List
3. Circular Linked List

1. Single Linked List


It is the most manageable type of linked list in which every node includes some data and the address part, which
means a pointer to the next node in the series. In a singly linked list, we can perform operations like insertion,
deletion, and traversal.

2. Doubly Linked List

When a node holds a data part and two addresses, it is known as a doubly-linked list. Two addresses means a
pointer to the previous node and the next node.

3. Circular Linked List

In a circular linked list, the last node of the series contains the address of the first node to make a circular chain.
Basic Operations In Linked List
When it comes to linked lists, there are five operations supported by the series or list.

 Traversal – Through this operation, we can access elements.


 Insertion – In this operation, elements can be added at the starting of the list.
 Deletion – In this operation, elements can be deleted at the starting of the list.
 Search – Through this operation, we can easily search for an element utilising the provided key.
 Sort – Through this operation, we can sort the nodes of the linked list.

Advantages of Linked Lists


 A linked list is dynamic, which means it will provide memory whenever needed.
 In a linked list, we can swiftly execute the operations like insertion and deletion.
 We can easily implement stacks and queues.
 It helps in reducing the access time.

Disadvantages of Linked Lists


 Sometimes the memory gets wasted because pointers need extra memory for storage.
 We can access elements in sequence. You cannot do this process in a random manner.
 In a linked list, reverse traversing is challenging.

Difference between Singly Linked List and Doubly Linked List


Both Singly linked list and Doubly linked list are the executions of a Linked list. The singly-linked list holds
data and a link to the next component. While in a doubly-linked list, every node includes a link to the previous
node. Let’s discuss some major differences between the Singly linked list and the Doubly linked list.
What is a Singly Linked List?
A singly linked list is a collection of nodes, where each node has two segments. The first segment belongs to
data, and the second segment belongs to the address or link.

The work of the data segment is to hold an actual piece of information, and the work of the link or address field
stores the address of the next node. Insertion, deletion, and traversing are some operations that we can perform
on a singly linked list.

What is a Doubly Linked List?


It is another popular type of linked list. A doubly linked list holds two addresses, and that is why it is known as
a doubly-linked list. The doubly linked list contains three segments: The first segment is data. The second and
third segments are pointers.

Here, the previous pointer contains the address of the previous node, and similarly, the other pointer contains
the address of the next node.

Difference between Singly Linked List and Doubly Linked List


S. Singly linked list Doubly linked list
No.

1 In case of singly linked lists, the complexity of insertion In case of doubly linked lists, the complexity of
and deletion is O(n) insertion and deletion is O(1)

2 The Singly linked list has two segments: data and link. The doubly linked list has three segments. First is
data and second, third are the pointers.

3 It permits traversal components only in one way. It permits two way traversal.

4 We mostly prefer a singly linked list for the execution of We can use a doubly linked list to execute binary
stacks. trees, heaps and stacks.

5 When we want to save memory and do not need to In case of better implementation, while searching,
perform searching, we prefer a singly linked list. we prefer a doubly linked list.

6 A singly linked list consumes less memory as compared The doubly linked list consumes more memory as
to the doubly linked list. compared to the singly linked list.

10.What is Array?
An array is a grouping of data elements or data items stored in contiguous memory. An array is one of the most
simple data structures where we can easily access the data element by only using its index number.

What is a Linked List?


A linked list is a linear and a non-primitive data structure in which each element is allocated dynamically, and
each element points to the next element. In other words, we can say that it is a data structure consisting of a
group of nodes that concurrently represent a sequence.

Difference between Array and Linked List


S.No. ARRAY LINKED LIST

An array is a grouping of data elements of equivalent A linked list is a group of entities called a node. The
1. data type. node includes two segments: data and address.

It stores the data elements in a contiguous memory It stores elements randomly, or we can say anywhere
2. zone. in the memory zone.

In the case of an array, memory size is fixed, and it is In the linked list, the placement of elements is
3. not possible to change it during the run time. allocated during the run time.

4. The elements are not dependent on each other. The data elements are dependent on each other.

5. The memory is assigned at compile time. The memory is assigned at run time.

It is easier and faster to access the element in an In a linked list, the process of accessing elements
6. array. takes more time.

In the case of an array, memory utilization is In the case of the linked list, memory utilization is
7. ineffective. effective.

When it comes to executing any operation like When it comes to executing any operation like
8 insertion, deletion, array takes more time. insertion, deletion, the linked list takes less time.
11.STACKS
 A Stack is linear data structure. A stack is a list of elements in which an element may be inserted or deleted only at
one end, called the top of the stack.
 Stack principle is LIFO (last in, first out). Which element inserted last on to the stack that element deleted first
from the stack.
A Stack is a linear data structure. In case of an array, random access is possible, i.e., any element of an array can
be accessed at any time, whereas in a stack, the sequential access is only possible. It is a container that
follows the insertion and deletion rule. It follows the principle LIFO (Last In First Out) in which the
insertion and deletion take place from one side known as a top. In stack, we can insert the elements of a
similar data type, i.e., the different data type elements cannot be inserted in the same stack. The two
operations are performed in LIFO, i.e., push and pop operation.
 Real life examples of stacks are:

Operations on stack:
 The two basic operations associated with stacks are:
1. Push:
 Push operation is used to add new elements into the stack.
 The new element is added at the topmost position of the stack.
 At the time of addition first check the stack is full or not. If the stack is full, it generates an error message "stack
overflow".
2. Pop:
 The pop operation is used to delete the topmost element from the stack.
 At the time of deletion first check the stack is empty or not. If the stack is empty, it generates an error message
"stack underflow".

While performing push and pop operations the following test must be conducted on the stack.
1) Stack is empty or not.
2) Stack is full or not.

Advantages of Stack
 A Stack helps to manage the data in the ‘Last in First out’ method.
 When the variable is not used outside the function in any program, the Stack can be used.
 It allows you to control and handle memory allocation and deallocation.
 It helps to automatically clean up the objects.
Disadvantages of Stack
 It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
 It has very limited memory.
 In Stack, random access is not possible.

Note:
 All insertions and deletions take place at the same end, so the last element added to the stack will be the first
element removed from the stack.
 When a stack is created, the stack base remains fixed while the stack top changes as elements are added and
removed.
 The most accessible element is the top and the least accessible element is the bottom of the stack.
 There are two types of Stacks: They are the Register Stack and the Memory Stack.

Implementation of stack:
 The stack should be represented in two ways:
1) Stack using array.
2) Stack using linked list.

12.Stack using array:


 Let us consider a stack with 6 elements capacity. This is called as the size of the stack.
 The number of elements to be added should not exceed the maximum size of the stack.
 If we attempt to add new element beyond the maximum size, we will encounter a stack overflow condition.
 Similarly, you cannot remove elements beyond the base of the stack. If such is the case, we will reach a stack
underflow condition.
push ():
 When an element is added to a stack, the operation is performed by push ().
 Below Figure shows the creation of a stack and addition of elements using push ().

 Initially top=-1, we can insert an element into the stack, increment the top value i.e., top=top+1.
 We can insert an element into the stack first check the condition is stack is full or not. i.e., top>=size-1. Otherwise
add the element in to the stack.

void push() Algorithm: Procedure for push():


{ Step 1: START
int x; Step 2: if top>=size-1 then
if(top >= n-1) Write “Stack is Overflow”
{ Step 3: Otherwise
printf("\nStack Overflow.."); 3.1: read data value ‘x’
return; 3.2: top=top+1;
} 3.3: stack[top]=x;
else Step 4: END
{
printf("\nEnter data: ");
scanf("%d", &x);
stack[top] = x;
top = top + 1;
printf("\nData Pushed into the stack");
}
}
pop():
 When an element is deleted from the stack, the operation is performed by pop().
 Below figure shows a stack initially with three elements and shows the deletion of elements using pop ().

 We can insert an element from the stack, decrement the top value i.e., top=top-1.
 We can delete an element from the stack first check the condition is stack is empty or not.
 i.e. top==-1. Otherwise remove the element from the stack.
Void pop() Algorithm: procedure pop():
{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is Underflow”
Printf(“Stack is Underflow”); Step 3: otherwise
} 3.1: print “deleted element”
else 3.2: top=top-1;
{ Step 4: END
printf(“Delete data %d”,stack[top]);
top=top-1;
}
}
display():
 This operation performed display the elements in the stack.
 We display the element in the stack check the condition is stack is empty or not i.e., top==-1. Otherwise display the
list of elements in the stack.

void display() Algorithm: procedure pop():


{ Step 1: START
If(top==-1) { Step 2: if top==-1 then
Printf(“Stack is Underflow”); Write “Stack is Underflow”
} Step 3: otherwise
else { 3.1: print “Display elements are”
printf(“Display elements are:); 3.2: for top to 0
for(i=top;i>=0;i--) Print ‘stack[i]’
printf(“%d”,stack[i]); Step 4: END
}
}
13.Source code for stack operations, using array:
#include<stdio.h>
#inlcude<conio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: {
push();
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
printf("\n\t EXIT POINT ");
break;
}
default: {
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1) {
printf("\n\tSTACK is over flow");
}
else {
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1) {
printf("\n\t Stack is under flow");
}
else {
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0) {
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

14. Stack using Linked List:


 Stack creating using an array is easy, but the drawback is that the array must be declared to have some fixed size. In
case the stack is a very small one or its maximum size is known in advance, then the array implementation of the
stack gives an efficient implementation. But if the array size cannot be determined in advance, then the other
alternative, i.e., linked representation, is used.
 The storage requirement of linked representation of the stack with n elements is O(n), and the typical time
requirement for the operations is O(1).
 In a linked stack, every node has two parts—one that stores data and another that stores the address of the next
node.
 The START pointer of the linked list is used as TOP. All insertions and deletions are done at the node pointed by TOP.
 If TOP = NULL, then it indicates that the stack is empty.
 The linked representation of a stack is shown in below figure.

Push Operation
 The push operation is used to insert an element into the stack. The new element is added at the topmost position of
the stack. Consider the linked stack shown in below figure.

 To insert an element with value 9, we first check if TOP=NULL. If this is the case, then we allocate memory for a new
node, store the value in its DATA part and NULL in its NEXT part. The new node will then be called TOP.
 However, if TOP!=NULL, then we insert the new node at the beginning of the linked stack and name this new node as
TOP.

 the algorithm to push an element into a linked stack.


 In Step 1, memory is allocated for the new node.
 In Step 2, the DATA part of the new node is initialized with the value to be stored in the node.
 In Step 3, we check if the new node is the first node of the linked list. is done by checking if TOP = NULL. In case the
IF statement evaluates to true, then NULL is stored in the NEXT part of the node and the new node is called TOP.
However, if the new node is not the first node in the list, then it is added before the first node of the list (that is, the
TOP node) and termed as TOP.

Pop Operation
 The pop operation is used to delete the topmost element from a stack.
 However, before deleting the value, we must first check if TOP=NULL, because if this is the case, then it means that
the stack is empty, and no more deletions can be done.
 If an attempt is made to delete a value from a stack that is already empty, an UNDERFLOW message is printed.
Consider the stack shown in below figure.

 In case TOP!=NULL, then we will delete the node pointed by TOP, and make TOP point to the second element of the
linked stack. Thus, the updated stack becomes as shown in below figure.

The algorithm to delete an element from a stack.


 In Step 1, we first check for the UNDERFLOW condition.
 In Step 2, we use a pointer PTR that points to TOP.
 In Step 3, TOP is made to point to the next node in sequence.
 In Step 4, the memory occupied by PTR is given back to the free pool.

Applications of stack:
a) Stack is used by compilers to check for balancing of parentheses, brackets, and braces.
b) Stack is used to evaluate a postfix expression.
c) Stack is used to convert an infix expression into postfix/prefix form.
d) In recursion, all intermediate arguments and return values are stored on the processor’s stack.
e) During a function call the return address and arguments are pushed onto a stack and on return they are popped off.

15.QUEUE
 A queue is linear data structure and collection of elements.
 The principle of queue is a “FIFO” or “First-in-first-out”.
 A queue is another special kind of list, where items are inserted at one end called the rear and deleted at the other
end called the front.
 Queue is an abstract data structure. A queue is a useful data structure in programming.
 A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first.

 The operations for a queue are analogues to those for a stack; the difference is that the insertions go at the end of
the list, rather than the beginning.

There are two similarities between the stack and queue:

o Linear data structure


Both the stack and queue are the linear data structure, which means that the elements are
stored sequentially and accessed in a single run.
o Flexible in size
Both the stack and queue are flexible in size, which means they can grow and shrink according
to the requirements at the run-time.

Operations on QUEUE:
 A queue is an object or more specifically an abstract data structure (ADT) that allows the following operations:
1. Enqueue or insertion: which inserts an element at the end of the queue.
2. Dequeue or deletion: which deletes an element at the start of the queue.

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.

Implementation of Queue:
The queue can be represented in two ways:
1. Queue using Array
2. Queue using Linked List

16.Queue using Array:


 Let us consider a queue, which can hold maximum of five elements. Initially the queue is empty.

 Now, insert 11 to the queue. Then queue status will be:

 Next, insert 22 to the queue. Then the queue status is:

 Again, insert another element 33 to the queue. The status of the queue is:

 Now, delete an element. The element deleted is the element at the front of the queue. So the status of the
queue is:

 Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is
deleted. The queue status is as follows:

 Now, insert new elements 44 and 55 into the queue. The queue status is:
 Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the rear crossed the
maximum size of the queue (i.e., 5). There will be queue full signal. The queue status is as follows:

 Now it is not possible to insert an element 66 even though there are two vacant positions in the linear queue.
 To overcome this problem the elements of the queue are to be shifted towards the beginning of the queue so
that it creates vacant position at the rear end. Then the FRONT and REAR are to be adjusted properly.
 The element 66 can be inserted at the rear end. After this operation, the queue status is as follows:

Note:
 This difficulty can overcome if we treat queue position with index 0 as a position that comes after position with
index 4 i.e., we treat the queue as a circular queue.
Queue operations using array:
1) enqueue() or insertion():which inserts an element at the end of the queue.
void insertion() Algorithm: Procedure for insertion():
{ Step-1:START
if(rear==max) Step-2: if rear==max then
printf("\n Queue is Full"); Write ‘Queue is full’
else Step-3: otherwise
{ 3.1: read element ‘queue[rear]’
printf("\n Enter no %d:",j++); Step-4:STOP
scanf("%d",&queue[rear++]);
}
}

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

void deletion() Algorithm: procedure for deletion():


{ Step-1:START
if(front==rear) { Step-2: if front==rear then
printf("\n Queue is empty"); Write’ Queue is empty’
} Step-3: otherwise
else { 3.1: print deleted element
printf("\n Deleted Element is Step-4:STOP
%d",queue[front++]);
x++;
}
}
3) dispaly(): which displays an elements in the queue.

void deletion() Algorithm: procedure for deletion():


{ Step-1:START
if(front==rear) { Step-2: if front==rear then
printf("\n Queue is empty"); Write’ Queue is empty’
} Step-3: otherwise
else { 3.1: for i=front to rear then
for(i=front; i<rear; i++) { 3.2: print ‘queue[i]’
printf("%d",queue[i]); Step-4:STOP
printf("\n");
}
}
}

17.Queue using Linked list:


 We can represent a queue as a linked list.
 In a queue data is deleted from the front end and inserted at the rear end.
 We can perform similar operations on the two ends of a list.
 We use two pointers front and rear for our linked queue implementation.
 The linked queue looks as shown in figure:

Applications of Queue:
1. It is used to schedule the jobs to be processed by the CPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing queue. Then the printer prints
those jobs according to first in first out (FIFO) basis.
3. Breadth first search uses a queue data structure to find an element from a graph.
4. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service
representative is free.
5. Handling of interrupts in real - time systems. The interrupts are handled in the same order as they arrive, First come
first served.

18.CIRCULAR QUEUE
 Once the queue gets filled up, no more elements can be added to it even if any element is removed from it
consequently. This is because during deletion, rear pointer is not adjusted.
 When the queue contains very few items and the rear pointer points to last element. i.e. rear=maxSize-1, we cannot
insert any more items into queue because the overflow condition satisfies.
 That means a lot of space is wasted. Frequent reshuffling of elements is time consuming. One solution to this is
arranging all elements in a circular fashion. Such structures are often referred to as Circular Queues.
 A circular queue is a queue in which all locations are treated as circular such that the first location CQ[0] follows the
last location CQ[max-1].
 A more efficient queue representation is obtained by regarding the array Q[MAX] as circular. Any number of items
could be placed on the queue.
 This implementation of a queue is called a circular queue because it uses its storage array as if it were a circle instead
of a linear list.

Circular Queue empty or underflow condition is


 if(front==-1)
 cout<<"Queue is empty";
 Circular Queue Full or overflow condition is
 if(front==(rear+1)%max)
 {
 cout<<"Circular Queue is full\n";
 }
 There are two problems associated with linear queue. They are:
 Time consuming: linear time to be spent in shifting the elements to the beginning of the queue.
 Signaling queue full: even if the queue is having vacant position.
 For example, let us consider a linear queue status as follows:

 Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the rear crossed the
maximum size of the queue (i.e., 5). There will be queue full signal. The queue status is as follows:

 This difficulty can be overcome if we treat queue position with index zero as a position that comes after position with
index four then we treat the queue as a circular queue.
 In circular queue if we reach the end for inserting elements to it, it is possible to insert new elements if the slots at
the beginning of the circular queue are empty.

Representation of Circular Queue:


 Let us consider a circular queue, which can hold maximum (MAX) of six elements. Initially the queue is empty.
 Now, insert 11 to the circular queue. Then circular queue status will be:

 Insert new elements 22, 33, 44 and 55 into the circular queue. The circular queue status is:

 Now, delete an element. The element deleted is the element at the front of the circular queue. So, 11 is deleted. The
circular queue status is as follows:

 Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is deleted.
The circular queue status is as follows:

 Again, insert another element 66 to the circular queue. The status of the circular queue is:
 Now, insert new elements 77 and 88 into the circular queue. The circular queue status is:

 Now, if we insert an element to the circular queue, as COUNT = MAX we cannot add the element to circular queue.
So, the circular queue is full.
 Operations on Circular queue:
1. enqueue() or insertion():This function is used to insert an element into the circular queue. In a circular queue,
the new element is always inserted at Rear position.
void insertCQ() Algorithm: procedure of insertCQ():
{ Step-1:START
int data; Step-2: if count==MAX then
if(count ==MAX) { Write “Circular queue is full”
printf("\n Circular Queue is Full"); Step-3:otherwise
} 3.1: read the data element
else { 3.2: CQ[rear]=data
printf("\n Enter data: "); 3.3: rear=(rear+1)%MAX
scanf("%d", &data); 3.4: count=count+1
CQ[rear] = data; Step-4:STOP
rear = (rear + 1) % MAX;
count ++;
printf("\n Data Inserted in the
Circular Queue ");
}
}
2. dequeue() or deletion():This function is used to delete an element from the circular queue. In a circular
queue, the element is always deleted from front position.
void deleteCQ() Algorithm: procedure of deleteCQ():
{ Step-1:START
if(count ==0) { Step-2: if count==0 then
printf("\n\nCircular Queue is Empty.."); Write “Circular queue is empty”
} Step-3:otherwise
else { 3.1: print the deleted element
printf("\n Deleted element from Circular Queue 3.2: front=(front+1)%MAX
is %d ", CQ[front]); 3.3: count=count-1
front = (front + 1) % MAX; Step-4:STOP
count --;
}
}
3. c.dispaly():This function is used to display the list of elements in the circular queue.
void displayCQ() Algorithm: procedure of displayCQ():
{ Step-1:START
int i, j; Step-2: if count==0 then
if(count ==0) { Write “Circular queue is empty”
printf("\nCircular Queue is Empty "); Step-3:otherwise
} 3.1: print the list of elements
else { 3.2: for i=front to j!=0
printf("\n Elements in Circular Queue 3.3: print CQ[i]
are: "); 3.4: i=(i+1)%MAX
j = count; Step-4:STOP
for(i = front; j != 0; j--)
{
printf("%d\t", CQ[i]);
i = (i + 1) % MAX;
}
}
}

19.Deque:
 In the preceding section we saw that a queue in which we insert items at one end and from which we remove items
at the other end.
 In this section we examine an extension of the queue, which provides a means to insert and remove items at both
ends of the queue. This data structure is a deque.
 The word deque is an acronym derived from double-ended queue. Below figure shows the representation of a
deque.

 Deque provides four operations.


1. enqueue_front: insert an element at front.
2. dequeue_front: delete an element at front.
3. enqueue_rear: insert element at rear.
4. dequeue_rear: delete element at rear.
 Below Figure shows the basic operations on a deque.
There are two variations of deque. They are:
 Input restricted deque (IRD): An Input restricted deque is a deque, which allows insertions at one end but allows
deletions at both ends of the list.
 Output restricted deque (ORD) : An output restricted deque is a deque, which allows deletions at one end but
allows insertions at both ends of the list.

20.Priority Queue:
 A priority queue is a collection of elements such that each element has been assigned a priority.
 A priority queue is a collection of zero or more elements. Each element has a priority or value.
 Unlike the queues, which are FIFO structures, the order of deleting from a priority queue is determined by the
 element priority.
 Elements are removed/deleted either in increasing or decreasing order of priority rather than in the order in
 which they arrived in the queue.
 There are two types of priority queues:
 Min priority queue: Collection of elements in which the items can be inserted arbitrarily, but only smallest element
can be removed.
 Max priority queue: Collection of elements in which insertion of items can be in any order but only largest element
can be removed.
 In priority queue, the elements are arranged in any order and out of which only the smallest or largest element
allowed to delete each time.
 The implementation of priority queue can be done using arrays or linked list. The data structure heap is used to
implement the priority queue effectively.
 We can insert an element in priority queue at the rare position.
 We can delete an element from the priority queue based on the element’s priority and such that the order in which
elements are deleted and processed comes from the following rules:
1. An element of higher priority is processed before any element of lower priority.
2. Two elements with same priority are processed according to the order in which they were added to the queue. It
follows FIFO or FCFS (First Comes First serve) rules.
 We always remove an element with the highest priority, which is given by the minimal integer priority assigned.
 A prototype of a priority queue is time sharing system: programs of high priority are processed first, and programs
with the same priority form a standard queue.
 An efficient implementation for the Priority Queue is to use heap, which in turn can be used for sorting purpose
called heap sort.

Priority queues are two types:


1. Ascending order priority queue: It is Lower priority number to high priority number.
 Examples: order is 1,2,3,4,5,6,7,8,9,10
2. Descending order priority queue: It is high priority number to lowest priority number.
 Examples: Order is 10,9,8,7,6,5,4,3,2,1

APPLICATIONS:
1. The typical example of priority queue is scheduling the jobs in operating system. Typically, OS allocates priority to jobs.
The jobs are placed in the queue and position of the job in priority queue determines their priority. In OS there are 3
jobs- real time jobs, foreground jobs and background jobs. The OS always schedules the real time jobs first. If there is
no real time jobs pending then it schedules foreground jobs. Lastly if no real time and foreground jobs are pending
then OS schedules the background jobs.
2. In network communication, the manage limited bandwidth for transmission the priority queue is used.
3. In simulation modelling to manage the discrete events the priority queue is used.

Implementation of Priority Queue:


 Implementation of priority queues are two types:
1. Through Queue (Using Array): In this case element is simply added at the rear end as usual. For deletion, the element
with highest priority is searched and then deleted.

2. Through sorted List (Using Linked List): In this case insertion is costly because the element inserts at the proper place
in the list based on the priority. Here deletion is easy since the element with highest priority will always be in the
beginning of the list.
21.Difference between stacks and Queues?
Parameter Stack Data Structure Queue Data Structure

Basics It is a linear data structure. The It is also a linear data structure. The objects are
objects are removed or inserted at the removed and inserted from two different ends.
same end.

Working Principle It follows the Last In, First Out It follows the First In, First Out (FIFO) principle. It
(LIFO) principle. It means that the last means that the first added element gets removed first
inserted element gets deleted at first. from the list.

Pointers It has only one pointer- the top. This It uses two pointers (in a simple queue) for reading and
pointer indicates the address of the writing data from both the ends- the front and
topmost element or the last inserted the rear. The rear one indicates the address of the last
one of the stack. inserted element, whereas the front pointer indicates
the address of the first inserted element in a queue.

Operations Stack uses push and pop as two of its Queue uses enqueue and dequeue as two of its
operations. The pop operation operations. The dequeue operation deletes the elements
functions to remove the element from from the queue, and the enqueue operation inserts the
the list, while the push operation elements in a queue.
functions to insert the element in a
list.

Structure Insertion and deletion of elements take It uses two ends- front and rear. Insertion uses the rear
place from one end only. It is called end, and deletion uses the front end.
the top.

Full Condition When top== max-1, it means that the When rear==max-1, it means that the queue is full.
Examination stack is full.
Empty Condition When top==-1, it indicates that the When front = rear+1 or front== -1, it indicates that the
Examination stack is empty. queue is empty.

Variants A Stack data structure does not have A Queue data structure has three types- circular queue,
any types. priority queue, and double-ended queue.

Visualization You can visualize the Stack as a You can visualize a Queue as a horizontal collection.
vertical collection.

Implementation The implementation is simpler in a The implementation is comparatively more complex in


Stack. a Queue than a stack.

Are Stacks or Queues Faster?


When it comes to data structures, it might be difficult to determine which is quicker between stacks and queues.
The response is based on the particular use case and the action being taken.

In general, operations that require adding and removing pieces from both ends of the data structure are faster
with queues. When only adding and removing elements at one end of the data structure is required, stacks are
faster.

Nevertheless, the performance difference between stacks and queues is typically insignificant, therefore the
decision should be made depending on the particular requirements of the programme.

The way elements are accessible in each data structure in turn determines how quickly stacks and queues
operate. The most recently inserted element is the first one to be removed when accessing items in a stack in a
Last-In-First-Out (LIFO) way. This makes adding and removing pieces from the top of the stack simple, but it
can take some time to access elements in the middle or at the bottom of the stack.

The first element added to an existing queue is the first one deleted when elements in a queue are accessed
using the First-In-First-Out (FIFO) principle. This makes it simple to add and remove components from the
queue's ends, but it may take some time to access elements in the middle of the queue.

In conclusion, the specific requirements of the programme should be taken into account when deciding between
stacks and queues. A queue would be a preferable option if the programme often adds and removes elements
from both ends of the data structure. A stack would be a preferable option if the programme often adds and
removes components from just one end of the data structure.

Application of Stack Data Structure


There are many applications of stack data structure in programming. Some of them are given below:

1. Stack is used for parenthesis matching while working with expressions.


2. Stacks are the data structures used to match the HTML tags in web development.
3. It is used in expression conversion. For example, infix to postfix or prefix to postfix.
4. It is an important aspect of Java virtual machine (JVM).
5. It is used for the Backtracking problem-solving method.
6. You can utilize it in string parsing or string reversal.
Application of Queue Data Structure
There are many applications of queue data structure in programming. Some of them are given below:

1. The queue is used as a waiting list when the resource is to be shared with multiple systems. For example, CPU
scheduling or disk scheduling.
2. It is used in the operating system for FCFS scheduling, semaphores, buffer for devices and spooling the printers.
3. Queues are used in routers and switches.
4. In networking, the queue is used when data is transferred asynchronously.
5. It is utilized in maintaining the playlist in media players.
6. It is also a part of the round-robin scheduling algorithm.

Basis of Linear Queue Circular Queue


comparison

Meaning The linear queue is a type of The circular queue is also a linear data
linear data structure that structure in which the last element of the
contains the elements in a Queue is connected to the first element,
sequential manner. thus creating a circle.

Insertion and In linear queue, insertion is In circular queue, the insertion and
Deletion done from the rear end, and deletion can take place from any end.
deletion is done from the front
end.

Memory space The memory space occupied by It requires less memory as compared to
the linear queue is more than linear queue.
the circular queue.

Memory The usage of memory is The memory can be more efficiently


utilization inefficient. utilized.

Order of It follows the FIFO principle in It has no specific order for execution.
execution order to perform the tasks.

22.What is a Binary Search Tree?


 In computer science, a binary search tree is an important term. It is also known as an ordered or sorted binary tree.
It contains a few properties like:
 The left subtree of a node includes only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.
Time Complexity in Binary Search Tree:
 When it comes to the binary search tree, the time complexity is O(log n) time where n is the number of nodes in the
tree. However, when it comes to the worst scenario, the time complexity for these operations is 0(n). In that
condition the tree becomes unbalanced.

Space Complexity in Binary Search Tree:


 The space complexity of a binary search tree is O(n).

Types of Traversals
 Types of Traversals the Binary Search Tree can be traversed in the following ways:
 In preorder traversal, we start from the current node before going on to the left and right nodes.
 In inorder traversal, we can traverse from the left node then hitting the current node and at the last right node.
 In postorder traversal, we can start by traversing from the left child node before the right child node and then the
current node.

Application Of Binary Search Tree


 Binary search tree is used to accomplish indexing and multi-level indexing.
 They are also capable of implementing various search algorithms.
 It aids in organizing a data stream.
 Self-balancing BSTs are used to implement TreeMap and TreeSet data structures.

Operation in Binary Search Tree


 Search Operation: Through this operation, we can search the location of some element in a binary search tree.
 Insertion Operation: Through this operation, we can add a node or element in the accurate place.
 Deletion Operation: When we delete a specific node or element from the binary search tree, it is known as deletion
operation.

Advantages:
 The binary search tree is fast in insertion and deletion etc when balanced.
 It is very effective, and its code is easier as compared to the link lists.

Disadvantages:
 The shape of the tree depends upon the order of insertion, and it can degenerate.
 In binary search trees, searching operations take a longer time.
 Comparison Right Binary Tree Vs Wrong Binary Search Tree
23.What is Graph?
 A graph is a non-linear data structure that permits you to define connections between different types of data
(nodes). Or we can say that a graph is a data structure that is built with the help of nodes or vertices and edges(arcs).

Types of Graphs
 Finite Graph: If a graph has a finite number of vertices and a finite number of edges, it is known as a finite graph.

 Infinite Graph: If a graph has an infinite number of vertices and an infinite number of edges, it is known as an infinite
graph.

Trivial Graph: If a finite graph has only a single vertex and no edge, it is known as a trivial graph.
Simple Graph: A graph that contains only one edge between the pair of vertices is known as a simple graph.

Multi Graph: If there are multiple edges or points between a set of vertices in a graph, it is known as a
multigraph.

Null Graph: A graph that does not include any edges in it is known as a null graph.
Complete Graph: A complete graph is also known as a full graph because each vertex’s degree should be n-1.

Pseudo Graph: If a graph has a self-loop with other edges it is known as a pseudo graph.

Regular Graph: If each vertex has the same degree, it is known as a regular graph.
Weighted Graph: A graph in which each edge has numbers or values is known as a weighted graph. It is a
special type of graph.

Directed Graph: A directed graph, also referred to as a digraph, is a collection of vertices combined by edges,
each with a direction.
Undirected Graph: An undirected graph comprises a set of nodes and links connecting them. The order of the two
connected vertices is irrelevant and has no direction. You can form an undirected graph with a finite number of
vertices and edges.

Connected Graph: If there is a path between one vertex of a graph data structure and any other vertex, the graph
is connected.
Graph Representation
There are two techniques to represent a graph:

1. Adjacency Matrix
In the adjacency matrix, each row and column define a vertex. It is a 2D array of V x V vertices.

2. Adjacency List
The index of the array defines a vertex, and every component in its linked list describes the other vertices that
form an edge with the vertex.

Application of Graphs in Data Structures

Following are some applications of graphs in data structures:


 Graphs are utilised in computer science to describe the flow of analysis and computation.
 It is utilised to describe networks of communication.
 It is used to define data organisation.

You might also like