DS UNIT I Final Notes On 15-08-2023
DS UNIT I Final Notes On 15-08-2023
Since the invention of computers, people have been using the term "Data" to refer
to Computer Information, either transmitted or stored. However, there is data that
exists in order types as well. Data can be numbers or texts written on a piece of
paper, in the form of bits and bytes stored inside the memory of electronic devices,
or facts stored within a person's mind. As the world started modernizing, this data
became a significant aspect of everyone's day-to-day life, and various
implementations allowed them to store it differently.
Let us consider an example where an employee name can be broken down into
three sub-items: First, Middle, and Last. However, an ID assigned to an employee
will generally be considered a single item.
In the example mentioned above, the items such as ID, Age, Gender, First, Middle,
Last, Street, Locality, etc., are elementary data items. In contrast, the Name and the
Address are group data items.
1
What is Data Structure?
Data Structure is a branch of Computer Science. The study of data structure allows
us to understand the organization of data and the management of the data flow in
order to increase the efficiency of any process or program. Data Structure is a
particular way of storing and organizing data in the memory of the computer so that
these data can easily be retrieved and efficiently utilized in the future when
required. The data can be managed in various ways, like the logical or
mathematical model for a specific organization of data is known as a data structure.
1. First, it must be loaded enough into the structure to reflect the definite
correlation of the data with a real-world object.
2. Second, the formation should be so straightforward that one can adapt to
process the data efficiently whenever necessary.
Some examples of Data Structures are Arrays, Linked Lists, Stack, Queue, Trees,
etc. Data Structures are widely used in almost every aspect of Computer Science,
i.e., Compiler Design, Operating Systems, Graphics, Artificial Intelligence, and
many more.
Data Structures are the main part of many Computer Science Algorithms as they
allow the programmers to manage the data in an effective way. It plays a crucial
role in improving the performance of a program or software, as the main objective
of the software is to store and retrieve the user's data as fast as possible.
Data Structures are the building blocks of any software or program. Selecting the
suitable data structure for a program is an extremely challenging task for a
programmer.
2
Attributes ID Name Gender Job Title
Entities with similar attributes form an Entity Set. Each attribute of an entity set has
a range of values, the set of all possible values that could be assigned to the specific
attribute.
The term "information" is sometimes utilized for data with given attributes of
meaningful or processed data.
As applications are becoming more complex and the amount of data is increasing
every day, which may lead to problems with data searching, processing speed,
multiple requests handling, and many more. Data Structures support different
methods to organize, manage, and store data efficiently. With the help of Data
Structures, we can easily traverse the data items. Data Structures provide
Efficiency, Reusability, and Abstraction.
1. Data Structures and Algorithms are two of the key aspects of Computer
Science.
2. Data Structures allow us to organize and store data, whereas Algorithms
allow us to process that data meaningfully.
3. Learning Data Structures and Algorithms will help us become better
Programmers.
4. We will be able to write code that is more effective and reliable.
5. We will also be able to solve problems more quickly and efficiently.
3
1. Correctness: Data Structures are designed to operate correctly for all kinds
of inputs based on the domain of interest. In order words, correctness forms
the primary objective of Data Structure, which always depends upon the
problems that the Data Structure is meant to solve.
2. Efficiency: Data Structures also requires to be efficient. It should process
the data quickly without utilizing many computer resources like memory
space. In a real-time state, the efficiency of a data structure is a key factor in
determining the success and failure of the process.
4
Figure 2: Classifications of Data Structures
1. Primitive Data Structures are the data structures consisting of the numbers
and the characters that come in-built into programs.
2. These data structures can be manipulated or operated directly by machine-
level instructions.
3. Basic data types like Integer, Float, Character, and Boolean come under
the Primitive Data Structures.
4. These data types are also called Simple data types, as they contain
characters that can't be divided further
5
4. Based on the structure and arrangement of data, we can divide these data
structures into two sub-categories -
a. Linear Data Structures
b. Non-Linear Data Structures
A data structure that preserves a linear connection among its data elements is
known as a Linear Data Structure. The arrangement of the data is done linearly,
where each element consists of the successors and predecessors except the first
and the last data element. However, it is not necessarily true in the case of memory,
as the arrangement may not be sequential.
Based on memory allocation, the Linear Data Structures are further classified into
two types:
1. Static Data Structures: The data structures having a fixed size are known as
Static Data Structures. The memory for these data structures is allocated at
the compiler time, and their size cannot be changed by the user after being
compiled; however, the data stored in them can be altered.
The Array is the best example of the Static Data Structure as they have a
fixed size, and its data can be modified later.
2. Dynamic Data Structures: The data structures having a dynamic size are
known as Dynamic Data Structures. The memory of these data structures is
allocated at the run time, and their size varies during the run time of the
code. Moreover, the user can change the size as well as the data elements
stored in these data structures at the run time of the code.
Linked Lists, Stacks, and Queues are common examples of dynamic data
structures
The following is the list of Linear Data Structures that we generally use:
1. Arrays
An Array is a data structure used to collect multiple data elements of the same data
type into one variable. Instead of storing multiple values of the same data types in
separate variable names, we could store all of them together into one variable. This
statement doesn't imply that we will have to unite all the values of the same data
type in any program into one array of that data type. But there will often be times
when some specific variables of the same data types are all related to one another
in a way appropriate for an array.
An Array is a list of elements where each element has a unique place in the list. The
data elements of the array share the same variable name; however, each carries a
6
different index number called a subscript. We can access any data element from
the list with the help of its location in the list. Thus, the key feature of the arrays to
understand is that the data is stored in contiguous memory locations, making it
possible for the users to traverse through the data elements of the array using their
respective indexes.
Figure 3. An Array
a. We can store a list of data elements belonging to the same data type.
b. Array acts as an auxiliary storage for other data structures.
c. The array also helps store data elements of a binary tree of the fixed count.
d. Array also acts as a storage of matrices.
2. Linked Lists
7
Figure 4. A Linked List
a. Singly Linked List: A Singly Linked List is the most common type of Linked
List. Each node has data and a pointer field containing an address to the next node.
b. Doubly Linked List: A Doubly Linked List consists of an information field
and two pointer fields. The information field contains the data. The first
pointer field contains an address of the previous node, whereas another
pointer field contains a reference to the next node. Thus, we can go in both
directions (backward as well as forward).
c. Circular Linked List: The Circular Linked List is similar to the Singly
Linked List. The only key difference is that the last node contains the address
of the first node, forming a circular loop in the Circular Linked List.
a. The Linked Lists help us implement stacks, queues, binary trees, and graphs
of predefined size.
b. We can also implement Operating System's function for dynamic memory
management.
c. Linked Lists also allow polynomial implementation for mathematical
operations.
d. We can use Circular Linked List to implement Operating Systems or
application functions that Round Robin execution of tasks.
e. Circular Linked List is also helpful in a Slide Show where a user requires to
go back to the first slide after the last slide is presented.
f. Doubly Linked List is utilized to implement forward and backward buttons
in a browser to move forward and backward in the opened pages of a
website.
3. Stacks
A Stack is a Linear Data Structure that follows the LIFO (Last In, First Out) principle
that allows operations like insertion and deletion from one end of the Stack, i.e.,
8
Top. Stacks can be implemented with the help of contiguous memory, an Array,
and non-contiguous memory, a Linked List. Real-life examples of Stacks are piles
of books, a deck of cards, piles of money, and many more.
The above figure represents the real-life example of a Stack where the operations
are performed from one end only, like the insertion and removal of new books from
the top of the Stack. It implies that the insertion and deletion in the Stack can be
done only from the top of the Stack. We can access only the Stack's tops at any
given time.
9
Figure 6. A Stack
4. Queues
A Queue is a linear data structure similar to a Stack with some limitations on the
insertion and deletion of the elements. The insertion of an element in a Queue is
10
done at one end, and the removal is done at another or opposite end. Thus, we can
conclude that the Queue data structure follows FIFO (First In, First Out) principle to
manipulate the data elements. Implementation of Queues can be done using
Arrays, Linked Lists, or Stacks. Some real-life examples of Queues are a line at the
ticket counter, an escalator, a car wash, and many more.
The above image is a real-life illustration of a movie ticket counter that can help us
understand the Queue where the customer who comes first is always served first.
The customer arriving last will undoubtedly be served last. Both ends of the Queue
are open and can execute different operations. Another example is a food court
line where the customer is inserted from the rear end while the customer is
removed at the front end after providing the service they asked for.
11
Figure 8. A Queue
1. Trees
The Tree data structure is a specialized method to arrange and collect data in the
computer to be utilized more effectively. It contains a central node, structural
12
nodes, and sub-nodes connected via edges. We can also say that the tree data
structure consists of roots, branches, and leaves connected.
Figure 9. A Tree
a. Binary Tree: A Tree data structure where each parent node can have at
most two children is termed a Binary Tree.
b. Binary Search Tree: A Binary Search Tree is a Tree data structure where
we can easily maintain a sorted list of numbers.
c. AVL Tree: An AVL Tree is a self-balancing Binary Search Tree where each
node maintains extra information known as a Balance Factor whose value is
either -1, 0, or +1.
d. B-Tree: A B-Tree is a special type of self-balancing Binary Search Tree
where each node consists of multiple keys and can have more than two
children.
13
e. Trees are responsible for implementing priority queues for priority-based
OS scheduling functions.
f. Trees are also responsible for parsing expressions and statements in the
compilers of different programming languages.
g. We can use Trees to store data keys for indexing for Database Management
System (DBMS).
h. Spanning Trees allows us to route decisions in Computer and
Communications Networks.
i. Trees are also used in the path-finding algorithm implemented in Artificial
Intelligence (AI), Robotics, and Video Games Applications.
2. Graphs
G = (V,E)
14
Figure 10. A Graph
Depending upon the position of the vertices and edges, the Graph s can be
classified into different types:
a. Null Graph: A Graph with an empty set of edges is termed a Null Graph.
b. Trivial Graph: A Graph having only one vertex is termed a Trivial
Graph.
c. Simple Graph: A Graph with neither self-loops nor multiple edges is
known as a Simple Graph.
d. Multi Graph: A Graph is said to be Multi if it consists of multiple edges
but no self-loops.
e. Pseudo Graph: A Graph with self-loops and multiple edges is termed a
Pseudo Graph.
f. Non-Directed Graph: A Graph consisting of non-directed edges is
known as a Non-Directed Graph.
g. Directed Graph: A Graph consisting of the directed edges between the
vertices is known as a Directed Graph.
h. Connected Graph: A Graph with at least a single path between every
pair of vertices is termed a Connected Graph.
i. Disconnected Graph: A Graph where there does not exist any path
between at least one pair of vertices is termed a Disconnected Graph.
j. Regular Graph: A Graph where all vertices have the same degree is
termed a Regular Graph.
k. Complete Graph: A Graph in which all vertices have an edge between
every pair of vertices is known as a Complete Graph.
l. Cycle Graph: A Graph is said to be a Cycle if it has at least three vertices
and edges that form a cycle.
m. Cyclic Graph: A Graph is said to be Cyclic if and only if at least one
cycle exists.
n. Acyclic Graph: A Graph having zero cycles is termed an Acyclic Graph.
o. Finite Graph: A Graph with a finite number of vertices and edges is
known as a Finite Graph.
p. Infinite Graph: A Graph with an infinite number of vertices and edges
is known as an Infinite Graph.
15
q. Bipartite Graph: A Graph where the vertices can be divided into
independent sets A and B, and all the vertices of set A should only be
connected to the vertices present in set B with some edges is termed a
Bipartite Graph.
r. Planar Graph: A Graph is said to be a Planar if we can draw it in a single
plane with two edges intersecting each other.
s. Euler Graph: A Graph is said to be Euler if and only if all the vertices are
even degrees.
t. Hamiltonian Graph: A Connected Graph consisting of a Hamiltonian
circuit is known as a Hamiltonian Graph.
16
For example, we can use the search operation to find the names of all the
employees who have the experience of more than 5 years.
3. Insertion: Insertion means inserting or adding new data elements to the
collection. For example, we can use the insertion operation to add the details
of a new employee the company has recently hired.
4. Deletion: Deletion means to remove or delete a specific data element from
the given list of data elements. For example, we can use the deleting
operation to delete the name of an employee who has left the job.
5. Sorting: Sorting means to arrange the data elements in either Ascending or
Descending order depending on the type of application. For example, we
can use the sorting operation to arrange the names of employees in a
department in alphabetical order or estimate the top three performers of the
month by arranging the performance of the employees in descending order
and extracting the details of the top three.
6. Merge: Merge means to combine data elements of two sorted lists in order
to form a single list of sorted data elements.
7. 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:
a. Compile-time
b. Run-time
For example, the malloc() function is used in C Language to create
data structure.
8. Selection: Selection means selecting a particular data from the available
data. We can select any particular data by specifying conditions inside the
loop.
9. Update: The Update operation allows us to update or modify the data in the
data structure. We can also update any particular data by specifying some
conditions inside the loop, like the Selection operation.
10. Splitting: The Splitting operation allows us to divide data into various
subparts decreasing the overall process completion time.
17
3. Data Structures allows the implementation of algorithms to search through
data (For example, search engine).
4. We can use the Data Structures to implement the algorithms to manipulate
data (For example, word processors).
5. We can also implement the algorithms to analyse data using Data Structures
(For example, data miners).
6. Data Structures support algorithms to generate the data (For example, a
random number generator).
7. Data Structures also support algorithms to compress and decompress the
data (For example, a zip utility).
8. We can also use Data Structures to implement algorithms to encrypt and
decrypt the data (For example, a security system).
9. With the help of Data Structures, we can build software that can manage files
and directories (For example, a file manager).
10. We can also develop software that can render graphics using Data
Structures. (For example, a web browser or 3D rendering software).
18
➢ Iteration
Sequence: The steps described in an algorithm are performed successively one by
one without skipping any step. The sequence of steps defined in an algorithm should
be simple and easy to understand. Each instruction of such an algorithm is executed,
because no selection procedure or conditional branching exists in a sequence
algorithm.
Example:
// adding two numbers
Step 1: start
Step 2: read a,b
Step 3: Sum=a+b
Step 4: write Sum
Step 5: stop
Selection: The sequence type of algorithms are not sufficient to solve the problems,
which involves decision and conditions. In order to solve the problem which involve
decision making or option selection, we go for Selection type of algorithm. The
general format of Selection type of statement is as shown below:
if(condition)
Statement-1;
else
Statement-2;
The above syntax specifies that if the condition is true, statement-1 will be executed
otherwise statement-2 will be executed. In case the operation is unsuccessful. Then
sequence of algorithm should be changed/ corrected in such a way that the system
will reexecute until the operation is successful
1.Write an algorithm for roots of a Quadratic Equation?
Example: Roots of a quadratic Equation
Step 1 : start
Step 2 : read a,b,c
Step 3 : if (a= 0) then step 4 else step 5
Step 4 : Write “ Given equation is a linear equation “
Step 5 : d=(b * b) _ (4 *a *c)
Step 6 : if ( d>0) then step 7 else step8
Step 7 : Write “ Roots are real and Distinct”
Step 8: if(d=0) then step 9 else step 10
19
Step 9: Write “Roots are real and equal”
Step 10: Write “ Roots are Imaginary”
Step 11: stop
Iteration: Iteration type algorithms are used in solving the problems which involves
repetition of statement. In this type of algorithms, a particular number of statements
are repeated ‘n’ no. of times.
Example1:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
Performance Analysis an Algorithm:
The Efficiency of an Algorithm can be measured by the following metrics.
i.Time Complexity:
The amount of time required for an algorithm to complete its execution is its time
complexity. An algorithm is said to be efficient if it takes the minimum (reasonable)
amount of time to complete its execution.
ii. Space Complexity:
The amount of space occupied by an algorithm is known as Space Complexity. An
algorithm is said to be efficient if it occupies less space and required the minimum
amount of time to complete its execution.
Part - C:
Stacks and Queues: Stack Representation using Arrays, operations on
stack, Applications of stacks - Factorial Calculation, Infix to postfix
Transformation, Evaluating Arithmetic Expressions. Queue
Representation using Arrays, operations on queues, Applications of
queues, Circular queues, Priority queues, Implementation of queue using
stack
20
UNIT-II
STACKS AND QUEUES
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.
As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.
Operations on stack:
While performing push and pop operations the following test must be conducted on the
stack.
a) Stack is empty or not b) stack is full or not
1. Push: Push operation is used to add new elements in to 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: Pop operation is used to delete elements 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".
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.
21
Representation of Stack (or) Implementation of stack:
The stack should be represented in two ways:
1. Stack using array
2. Stack using linked list
Initially top=-1, we can insert an element in to the stack, increment the top value i.e
top=top+1. We can insert an element in to 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.
22
2.Pop(): When an element is taken off 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.
3.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.
23
void display() 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 “Display elements are”
else 3.2: for top to 0
{ Print ‘stack[i]’
printf(“Display elements are:); Step 4: END
for(i=top;i>=0;i--)
printf(“%d”,stack[i]);
}
}
#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()
{
//clrscr();
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:
{
10
24
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)
{
11
25
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");
}
Applications of stack:
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.
12
26
An algebraic expression can be represented using three different notations. They are infix,
postfix and prefix notations:
Infix: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator in between the two operands.
Example: A + B
Prefix: It is the form of an arithmetic notation in which we fix (place) the arithmetic
operator before (pre) its two operands. The prefix notation is called as polish notation.
Example: + A B
Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator after (post) its two operands. The postfix notation is called as suffix notation and is
also referred to reverse polish notation.
Example: A B +
Conversion from infix to postfix:
Procedure to convert from infix expression to postfix expression is as follows:
1. Scan the infix expression from left to right.
2. a) If the scanned symbol is left parenthesis, push it onto the stack.
b) If the scanned symbol is an operand, then place directly in the postfix expression
(output).
c) If the symbol scanned is a right parenthesis, then go on popping all the items from the
stack and place them in the postfix expression till we get the matching left parenthesis.
d) If the scanned symbol is an operator, then go on removing all the operators from the
stack and place them in the postfix expression, if and only if the precedence of the
operator which is on the top of the stack is greater than (or greater than or equal) to the
precedence of the scanned operator and push the scanned operator onto the stack
otherwise, push the scanned operator onto the stack.
The three important features of postfix expression are:
1. The operands maintain the same order as in the equivalent infix expression.
2. The parentheses are not needed to designate the expression unambiguously.
3. While evaluating the postfix expression the priority of the operators is no longer relevant.
13
27
Evaluation of postfix expression:
The postfix expression is evaluated easily by the use of a stack.
1. When a number is seen, it is pushed onto the stack;
2. When an operator is seen, the operator is applied to the two numbers that are
popped from the stack and the result is pushed onto the stack.
3. When an expression is given in postfix notation, there is no need to know any
precedence rules; this is our obvious advantage.
14
28
15
29
QUEUE
A queue is linear data structure and collection of elements. 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. The principle of queue is a “FIFO” or “First-in-first-out”.
Queue is an abstract data structure. A queue is a useful data structure in programming. It is
similar to the ticket queue outside a cinema hall, where the first person entering the queue
is the first person who gets the ticket.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first.
More real-world examples can be seen as queues at the ticket windows and bus-stops and
our college library.
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.
Operations on QUEUE:
A queue is an object or more specifically an abstract data structure (ADT) that allows the
following operations:
Enqueue or insertion: which inserts an element at the end of the queue.
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.
16
30
Representation of Queue (or) Implementation of Queue:
The queue can be represented in two ways:
1. Queue using Array
2. Queue using Linked List
1.Queue using Array:
Let us consider a queue, which can hold maximum of five elements. Initially the queue is
empty.
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:
17
31
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:
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.
18
32
c.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
{ Write’ Queue is empty’
printf("\n Queue is empty"); Step-3: otherwise
} 3.1: for i=front to rear then
else 3.2: print ‘queue[i]’
{ Step-4:STOP
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
}
}
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.
19
33
CIRCULAR QUEUE
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.
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:
20
34
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:
21
35
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.
a.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.
22
36
b.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():
{
if(count ==0) Step-1:START
{ 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
{ 3.2: front=(front+1)%MAX
printf("\n Deleted element from Circular 3.3: count=count-1
Queue is %d ", CQ[front]); Step-4:STOP
front = (front + 1) % MAX;
count --;
}
}
c.dispaly():This function is used to display the list of elements in the circular queue.
void displayCQ() Algorithm: procedure of displayCQ():
{
int i, j; Step-1:START
if(count ==0) Step-2: if count==0 then
{ Write “Circular queue is empty”
printf("\n\n\t Circular Queue is Empty "); Step-3:otherwise
} 3.1: print the list of elements
else 3.2: for i=front to j!=0
{ 3.3: print CQ[i]
printf("\n Elements in Circular Queue are: 3.4: i=(i+1)%MAX
"); Step-4:STOP
j = count;
for(i = front; j != 0; j--)
{
printf("%d\t", CQ[i]);
i = (i + 1) % MAX;
}
}
}
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.
23
37
deque provides four operations. Below Figure shows the basic operations on a deque.
• enqueue_front: insert an element at front.
• dequeue_front: delete an element at front.
• enqueue_rear: insert element at rear.
• dequeue_rear: delete element at rear.
24
38
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
2. Through sorted List (Using Linked List): In this case insertion is costly because the
element insert 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.
25
39
1. Difference between stacks and Queues?
stacks Queues
1.A stack is a linear list of elements in which 1.A Queue is a linerar list of elements in which
the element may be inserted or deleted at the elements are added at one end and
one end. deletes the elements at another end.
2. . In Queue the element which is inserted
2. In stacks, elements which are inserted first is the element deleted first.
last is the first element to be deleted.
3. Queues are called FIFO (First In First
3.Stacks are called LIFO (Last In First Out)list.
Out)list
4. In Queue elements are removed in the
4.In stack elements are removed in reverse same order in which thy are inserted.
order in which thy are inserted.
5. Suppose the elements a,b,c,d,e are inserted
5.suppose the elements a,b,c,d,e are in the Queue, the deletion of elements will be
inserted in the stack, the deletion of in the same order in which thy are inserted.
elements will be e,d,c,b,a.
6. In Queue there are two pointers one for
6.In stack there is only one pointer to insert insertion called “Rear” and another for
and delete called “Top”. deletion called “Front”.
26
40
incremented by one.
11.The conceptual view of Stack is as
follows: 11.The conceptual view of Queue is as
follows:
27
41