0% found this document useful (0 votes)
21 views133 pages

Communication Skills

Info about communication skills

Uploaded by

mhaskarvikas86
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)
21 views133 pages

Communication Skills

Info about communication skills

Uploaded by

mhaskarvikas86
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/ 133

Data Strucure

Module 2 : Stack and Queues

Faculty Name:
Index -

Stack: ADT, Representation, Operations, Applications of Stack. ADT of Queue, Representation of Queue,
Operations on Queue, Circular Queue, Priority Queue, Applications of Queue. 5

22

2
Lecture 5

Introduction, ADT of Stack,


Operations on Stack
Stack

Stack is an important data structure which stores its elements in an ordered manner.
Consider the pile of plates where one plate is placed on top of another as shown in Fig.

Stack of plates

Now, when you want to remove a plate, you remove the topmost plate first.
Hence, you can add and remove an element (i.e., a plate) only at/from one position which is the topmost position.

4
Introduction to Stack (Real World Example)

Stack of plates in cafeteria.

Pack of Tennis Ball

Mathematical puzzle called,


Tower of Hanoi, where we have
three rods or three pegs and
multiple disks

5 Lecture 3: Introduction to Stack


Stack

• A stack is a linear data structure which uses the same principle, i.e., the elements in a stack are
added and removed only from one end, which is called the TOP.
• Hence, a stack is called a LIFO (Last-In-First-Out) data structure, as the element that was inserted
last is the first one to be taken out.
• In other words, a stack can be defined as a container in which insertion and deletion can be done
from the one end known as the top of the stack.

6
Representation of Stack

ARRAY REPRESENTATION OF STACKS


• In the computer’s memory, stacks can be represented as a linear array.
• Every stack has a variable called TOP associated with it, which is used to store the address of the
topmost element of the stack.
• It is this position where the element will be added to or deleted from.
• There is another variable called MAX, which is used to store the maximum number of elements that
the stack can hold.
• If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then the stack is full. (why
we have written MAX–1. It is because array indices start from 0.)
• The stack in Fig. shows that TOP = 4, so insertions and deletions will be done at this position.
• In the above stack, five more elements can still be stored.

7
Operations on Stack

• A stack supports three basic operations: push, pop, and peek.


• The push operation adds an element to the top of the stack and the pop operation removes the element from the
top of the stack.
• The peek operation returns the value of the topmost element of the stack.

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.
• However, before inserting the value, we must first check if TOP=MAX–1, because if that is the case, then the stack
is full and no more insertions can be done.
• If an attempt is made to insert a value in a stack that is already full, an OVERFLOW message is printed.
• Consider the stack given in Fig.

8
Operations on Stack

• To insert an element with value 6, we first check if TOP=MAX–1.


• If the condition is false, then we increment the value of TOP and store the new element at the position given by
stack[TOP].
• Thus, the updated stack becomes as shown in Fig.

Stack after insertion

9
Operations on Stack

Algorithm to insert an element in a stack

Figure shows the algorithm to insert an element in a stack.


In Step 1, we first check for the OVERFLOW condition.
In Step 2, TOP is incremented so that it points to the next location in the array.
In Step 3, the value is stored in the stack at the location pointed by TOP.

10
Operation: Pushing into a Stack

11 Lecture 3: Introduction to Stack


Operation: Popping from a Stack

12 Lecture 3: Introduction to Stack


Demo

Exercise

http://ds1-iiith.vlabs.ac.in/data-structures-1/exp/stacks-
queues/exp.html#Stacks%20:%20Arrays

Problem:
http://ds1-iiith.vlabs.ac.in/data-structures-1/exp/stacks-
queues/exp.html#Stacks%20:%20Demo

13 Lecture 3: Introduction to Stack


Algorithm : PUSH

Step 1: If TOP=Max-1,then

print “overflow”

[End of If]

Step 2: Set TOP=TOP+1

Step 3: Set Stack[TOP]=value


top
Step 4:End
top

top

14 Lecture 3: Introduction to Stack


Algorithm : POP

Step 1: If TOP=NULL, then

print “Underflow”

[End of If]
top
Step 2: Set value=Stack[TOP]
top
Step 3: Set TOP=TOP-1
top
Step 4:End

15 Lecture 3: Introduction to Stack


Algorithm : PEEP

Step 1: If TOP=NULL, then

print “Underflow”

[End of If]

top
Step 2: Return value=Stack[TOP]

Step 3:End

16 Lecture 3: Introduction to Stack


Operations on Stack

Pop Operation
• The pop operation is used to delete the topmost element from the stack.
• However, before deleting the value, we must first check if TOP=NULL because if that is the case, then it means
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 given in Fig.

Stack

17
Operations on Stack

• To delete the topmost element, we first check if TOP=NULL.


• If the condition is false, then we decrement the value pointed by TOP.
• Thus, the updated stack becomes as shown in Fig.

Stack after deletion

18
Operations on Stack

Figure shows the algorithm to delete an element from a stack.


• In Step 1, we first check for the UNDERFLOW condition.
• In Step 2, the value of the location in the stack pointed by TOP is stored in VAL.
• In Step 3, TOP is decremented.

Algorithm to delete an element from a stack

19
Applications of Stack

Applications of Stack

•Balancing of symbols: Stack is used for balancing a symbol.


•For example, we have the following program:

int main()
{
cout<<"Hello";
cout<<“RAIT";
}

As we know, each program has an opening and closing braces; when the opening braces come, we push the
braces in a stack, and when the closing braces appear, we pop the opening braces from the stack. Therefore, the
net value comes out to be zero. If any symbol is left in the stack, it means that some syntax occurs in a program.

20
Applications of Stack

• Reversing a list
• Parentheses checker
• Conversion of an infix expression into a postfix expression
• Evaluation of a postfix expression
• Conversion of an infix expression into a prefix expression
• Evaluation of a prefix expression
• Recursion
• Tower of Hanoi

21
Applications of Stack

Parentheses checker
• Stacks can be used to check the validity of parentheses in any algebraic expression.
• For example, an algebraic expression is valid if for every open bracket there is a corresponding closing bracket.
• For example, the expression (A+B} is invalid but an expression {A + (B – C)} is valid.

Evaluation of Arithmetic Expressions


Infix expression: The expression of the form “a operator b” (a + b) i.e., when an operator is in-between every pair of
operands.
Postfix expression: The expression of the form “a b operator” (ab+) i.e., When every pair of operands is followed by
an operator.

22
Applications of Stack

Why postfix representation of the expression?


• The compiler scans the expression either from left to right or from right to left.
Consider the expression: a + b * c + d
•The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to
add a to it.
•The result is then added to d after another scan.

• The repeated scanning makes it very inefficient.


• Infix expressions are easily readable and solvable by humans whereas the computer cannot differentiate the
operators and parenthesis easily so, it is better to convert the expression to postfix(or prefix) form before
evaluation.
• The corresponding expression in postfix form is abc*+d+.
• The postfix expressions can be evaluated easily using a stack.

23
Applications of Stack

Convert an Infix expression to a Postfix expression

To convert infix expression to postfix expression, use the stack data structure.
Scan the infix expression from left to right.
Whenever we get an operand, add it to the postfix expression and if we get an operator or parenthesis add it to the
stack by maintaining their precedence.

24
Applications of Stack

1.Scan the infix expression from left to right.


2.If the scanned character is an operand, put it in the postfix expression.
3.Otherwise, do the following
• If the precedence and associativity of the scanned operator are greater than the precedence and associativity
of the operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘
operator is right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-associative].
• Check especially for a condition when the operator at the top of the stack and the scanned operator
both are ‘^‘. In this condition, the precedence of the scanned operator is higher due to its right
associativity. So it will be pushed into the operator stack.
• In all the other cases when the top of the operator stack is the same as the scanned operator, then pop
the operator from the stack because of left associativity due to which the scanned operator has less
precedence.
• Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the
scanned operator.
• After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping
then stop there and push the scanned operator in the stack.)

25
Applications of Stack

4.If the scanned character is a ‘(‘, push it to the stack.


5.If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the
parenthesis.
6.Repeat steps 2-5 until the infix expression is scanned.
7.Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty.
8.Finally, print the postfix expression.

26
Applications of Stack

27
Applications of Stack

28
Applications of Stack

•String reversal:
• Stack is also used for reversing a string. For example, we want to reverse a “RAIT" string, so we can achieve this
with the help of a stack.
• First, we push all the characters of the string in a stack until we reach the null character.
• After pushing all the characters, we start taking out the character one by one until we reach the bottom of the
stack.

•UNDO/REDO:
• It can also be used for performing UNDO/REDO operations.
•For example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an editor is
abc.
•So, there are three states, a, ab, and abc, which are stored in a stack.
•There would be two stacks in which one stack shows UNDO state, and the other shows REDO state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement pop operation.

29
Applications of Stack

•String reversal: Stack is also used for reversing a string. For example, we want to reverse a “RAIT" string, so we
can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.
After pushing all the characters, we start taking out the character one by one until we reach the bottom of the stack.

•UNDO/REDO: It can also be used for performing UNDO/REDO operations.


•For example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an editor is
abc.
•So, there are three states, a, ab, and abc, which are stored in a stack.
•There would be two stacks in which one stack shows UNDO state, and the other shows REDO state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement pop operation.

30
Applications of Stack

•Recursion: The recursion means that the function is calling itself again.
•To maintain the previous states, the compiler creates a system stack in which all the previous records of the
function are maintained.

•DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the stack data structure.

•Backtracking:
•Suppose we have to create a path to solve a maze problem.
•If we are moving in a particular path, and we realize that we come on the wrong way.
•In order to come at the beginning of the path to create a new path, we have to use the stack data structure.

•Expression conversion:
•Stack can also be used for expression conversion.
•This is one of the most important applications of stack.
•The list of the expression conversion is given below:

31
Applications of Stack

32
Applications of Stack

Conversion of an Infix Expression into a Postfix Expression

33
Applications of Stack

Evaluation of a Postfix Expression

34
C Program for evaluation of postfix expression

35
C Program for evaluation of postfix expression

36
C Program for evaluation of postfix expression

37
Applications of Stack

Let us now take an example that makes use of this algorithm.

Consider the infix expression given as 9 – ((3 * 4) + 8) / 4.


Evaluate the expression.
The infix expression 9 – ((3 * 4) + 8) / 4 can be written as 9 3 4 * 8 + 4 / – using postfix notation.

38
Applications of Stack

Conversion of an Infix Expression into a Prefix Expression


There are two algorithms to convert an infix expression into its equivalent prefix expression. The
first algorithm is given in Fig. 1, while the second algorithm is shown in Fig. 2.

Fig. 1

39
Applications of Stack

40
Algorithm for evaluation of a prefix expression

Evaluation of a Prefix Expressions

41
Applications of Stack

42
Applications of Stack

43
Applications of Stack

•Memory management:
•The stack manages the memory.
•The memory is assigned in the contiguous memory blocks.
•The memory is known as stack memory as all the variables are assigned in a function call stack memory.
•The memory size assigned to the program is known to the compiler.
•When the function is created, all its variables are assigned in the stack memory.
•When the function completed its execution, all the variables assigned in the stack are released.

44
Operations on Stack

Stack works on the LIFO pattern.


As we can observe in the below figure there are five memory blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty.
We have taken the stack of size 5 as shown below in which we are pushing the elements one by one until the stack
becomes full.

45
Operations on Stack

46
Operations on 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.

47
Operations on Stack

48
LINKED REPRESENTATION OF STACK

• Stack can be created using an array, This technique of creating a stack 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.
• 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

49
LINKED REPRESENTATION OF STACK

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).

• The O(n) notation means that the runtime complexity of your algorithm has a linear relationship with the size of
input data.
• If the size of input data is increased by 2, then the runtime complexity of your algorithm will be increased by 2 as
well. O(1) means the running time of an algorithm is independent of the input size and is bounded by a constant
'c'.

50
LINKED REPRESENTATION OF STACK

The linked representation of a stack is shown in Fig

OPERATIONS ON A LINKED STACK


A linked stack supports all the three stack operations, that is, push, pop, and peek.

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 Fig.

Linked stack

51
LINKED REPRESENTATION OF STACK

• 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.
• Thus, the updated stack becomes as shown in Fig.

Linked stack after inserting a new node

52
LINKED REPRESENTATION OF STACK

• Figure shows 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. This 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.

53
LINKED REPRESENTATION OF STACK

54
LINKED REPRESENTATION OF STACK

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 Fig.

Linked stack

55
LINKED REPRESENTATION OF STACKs

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 Fig.

Linked stack after deletion of the topmost element

56
LINKED REPRESENTATION OF STACKs

Figure shows 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.

Algorithm to delete an
element from a linked stack

57
LINKED REPRESENTATION OF STACKs

MULTIPLE STACKS
• While implementing a stack using an array, the size of the array must be known in advance.
• If the stack is allocated less space, then frequent OVERFLOW conditions will be encountered.
• To deal with this problem, the code will have to be modified to reallocate more space for the array.
• In case we allocate a large amount of space for the stack, it may result in sheer wastage of
memory.
• Thus, there lies a trade-off between the frequency of overflows and the space allocated.
• So, a better solution to deal with this problem is to have multiple stacks or to have more than one stack in the
same array of sufficient size.
• Figure illustrates this concept.

58
LINKED REPRESENTATION OF STACKs

• In Fig., an array STACK[n] is used to represent two stacks, Stack A and Stack B.
• The value of n is such that the combined size of both the stacks will never exceed n.
• While operating on these stacks, it is important to note one thing—Stack A will grow from left to right, whereas
Stack B will grow from right to left at the same time.

• Extending this concept to multiple stacks, a stack can also be used to represent n number of
stacks in the same array.
• That is, if we have a STACK[n], then each stack I will be allocated an equal amount of space bounded by indices
b[i] and e[i].
• This is shown in Fig.

Multiple stacks

59
LINKED REPRESENTATION OF STACKs

60
LINKED REPRESENTATION OF STACKs

61
LINKED REPRESENTATION OF STACKs

62
LINKED REPRESENTATION OF STACKs

63
Queue

INTRODUCTION
• People moving on an escalator. The people who got on the escalator first will be the first one
to step out of it.
• People standing outside the ticketing window of a cinema hall. The first person in the line
will get the ticket first and thus will be the first one to move out of it.
• Luggage kept on conveyor belts. The bag which was placed first will be the first to come out
at the other end.
• Cars lined at a toll bridge. The first car to reach the bridge will be the first to leave.

64
Introduction to Queues (Real World Example)

OUT

IN

STACK – Last In First Out (LIFO) QUEUE– First In First Out (FIFO)

65 Lecture 7 ADT of Queue, Operations on Queue


Introduction to Queues (Real World Example)

Deletion
@Front
OUT End

IN

Insertion
@ Rear
End QUEUE– First In First Out (FIFO)

66 Lecture 7 ADT of Queue, Operations on Queue


Queue

A Queue is defined as a linear data structure that is open at both ends and the operations are performed in First In
First Out (FIFO) order.
The elements in a queue are added at one end called the REAR and removed from the other end called the FRONT

67
Queue

ARRAY REPRESENTATION OF QUEUES


Queues can be easily represented using linear arrays
Operations on Queues
• In Fig. 1, FRONT = 0 and REAR = 5.
• Suppose we want to add another element with value 45, then REAR would be incremented by 1 and the value
would be stored at the position pointed by REAR.
• The queue after addition would be as shown in Fig. 2.
Here, FRONT = 0 and REAR = 6.
• Every time a new element has to be added, we repeat the same procedure.
• If we want to delete an element from the queue, then the value of FRONT will be incremented.
• Deletions are done from only this end of the queue.
• The queue after deletion will be as shown in Fig. 3.

68
Queue

Queue

Queue after insertion of a new element

Queue after deletion of an element

69
Queue

The algorithm to insert an element in a queue.

➢ In Step 1, we first check for the overflow condition.


➢ In Step 2, we check if the queue is empty.
➢ In case the queue is empty, then both FRONT and REAR are set to zero, so that the
new value can be stored at the 0th location.
➢ Otherwise, if the queue already has some values, then REAR is incremented so
that it points to the next location in the array.
➢ In Step 3, the value is stored in the queue at the location pointed by REAR.

70
Queue

Algorithm to insert an element in a queue

71
Queue

The algorithm to delete an element from a queue.


In Step 1, we check for underflow condition.
An underflow occurs if FRONT = –1 or FRONT > REAR.
However, if queue has some values, then FRONT is incremented so that it now points to the next value in the queue.

72
Queue

Algorithm to delete an element from a queue

73
C Program to implement linear queue

74
C Program to implement linear queue

75
C Program to implement linear queue

76
C Program to implement linear queue

77
C Program to implement linear queue

78
C Program to implement linear queue

79
C Program to implement linear queue

80
C Program to implement linear queue

81
C Program to implement linear queue

82
C Program to implement linear queue

83
C Program to implement linear queue

84
C Program to implement linear queue

85
Queue

When REAR = MAX – 1, where MAX is the size of the queue, we have an overflow condition.

If FRONT = –1 and REAR = –1, it means there is no element in the queue

86
LINKED REPRESENTATION OF QUEUE

• A queue is created using an array.


• Although this technique of creating a queue is easy, its drawback is that the array must be declared to have
some fixed size.
• If we allocate space for 50 elements in the queue and it hardly uses 20–25 locations, then half of the space will
be wasted.
• And in case we allocate less memory locations for a queue that might end up growing large and large, then a lot
of re-allocations will have to be done, thereby creating a lot of overhead and consuming a lot of time.
• The storage requirement of linked representation of a queue with n elements is O(n) and the typical time
requirement for operations is O(1).

• In a linked queue, every element has two parts, one that stores the data and another that stores the address of
the next element.
• The START pointer of the linked list is used as FRONT.
• Here, we will also use another pointer called REAR, which will store the address of the last element in the queue.
• All insertions will be done at the rear end and all the deletions will be done at the front end.
• If FRONT = REAR = NULL, then it indicates that the queue is empty.

87
LINKED REPRESENTATION OF QUEUE

• In a linked queue, every element has two parts, one that stores the data and another that stores the address of
the next element.
• The START pointer of the linked list is used as FRONT.
• Here, we will also use another pointer called REAR, which will store the address of the last element in the queue.
• All insertions will be done at the rear end and all the deletions will be done at the front end.
• If FRONT = REAR = NULL, then it indicates that the queue is empty.

Linked queue

88
LINKED REPRESENTATION OF QUEUE

Operations on Linked Queues


• A queue has two basic operations: insert and delete.
• The insert operation adds an element to the end of the queue, and the delete operation removes an element
from the front or the start of the queue.
• Apart from this, there is another operation peek which returns the value of the first element of the queue.
• The insert operation is used to insert an element into a queue.
• The new element is added as the last element of the queue.
• Consider the linked queue shown in Fig.

89
LINKED REPRESENTATION OF QUEUE

• To insert an element with value 9, we first check if FRONT=NULL.


• If the condition holds, then the queue is empty. So, 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 both FRONT and rear.
• However, if FRONT != NULL, then we will insert the new node at the rear end of the linked queue and name this new
node as rear.
• Thus, the updated queue becomes as shown in Fig.

90
LINKED REPRESENTATION OF QUEUE

• Figure shows the algorithm to insert an element in a linked queue.

• In Step 1, the 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 queue.
• This is done by checking if FRONT = NULL.
• If this is the case, then the new node is tagged as FRONT as well as REAR.
• Also NULL is stored in the NEXT part of the node (which is also the FRONT and the REAR node).
• However, if the new node is not the first node in the list, then it is added at the REAR end of the linked queue
(or the last node of the queue).

91
LINKED REPRESENTATION OF QUEUE

Algorithm to insert an element in a linked queue

92
LINKED REPRESENTATION OF QUEUE

Delete Operation
• The delete operation is used to delete the element that is first inserted in a queue, i.e., the element whose address is
stored in FRONT.
• However, before deleting the value, we must first check if FRONT=NULL because if this is the case, then the queue is
empty and no more deletions can be done.
• If an attempt is made to delete a value from a queue that is already empty, an underflow message is printed.
• Consider the queue shown in Fig.

Linked queue

93
LINKED REPRESENTATION OF QUEUE

• Figure shows the algorithm to delete an element from a linked queue.


• In Step 1, we first check for the underflow condition.
• If the condition is true, then an appropriate message is displayed, otherwise in Step 2, we use a pointer PTR that
• points to FRONT.
• In Step 3, FRONT 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.

Algorithm to delete an element


from a linked queue

94
LINKED REPRESENTATION OF QUEUE

95
LINKED REPRESENTATION OF QUEUE

• To delete an element, we first check if FRONT=NULL.


• If the condition is false, then we delete the first node pointed by FRONT.
• The FRONT will now point to the second element of the linked queue.
• Thus, the updated queue becomes as shown in Fig

96
Queue

97
Circular Queue

Types of Queues in Data Structure


There are four different types of queues in data structures:
•Simple Queue
•Circular Queue
•Priority Queue
•Double-Ended Queue (Deque)

Circular Queue Data Structure


• A circular queue is the extended version of a regular queue where the last element is connected to the first
element.
• Thus forming a circle-like structure.
• The operations are performed based on FIFO (First In First Out) principle.
• It is also called ‘Ring Buffer’.

98
Circular Queue

99
Circular Queue

• The circular queue solves the major limitation of the normal queue.
• In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we can not
insert the next element even if there is a space in front of queue.

Here, indexes 0 and 1 can only be used after resetting the queue (deletion of all elements).
This reduces the actual size of the queue.

100
Circular Queue

Operations on Circular Queue:


•Front: Get the front item from the queue.
•Rear: Get the last item from the queue.
•enQueue(value) This function is used to insert an element into the circular queue. In a circular queue, the new
element is always inserted at the rear position.
• Check whether the queue is full – [i.e., the rear end is in just before the front end in a circular manner].
• If it is full then display Queue is full.
• If the queue is not full then, insert an element at the end of the queue.

•deQueue() This function is used to delete an element from the circular queue. In a circular queue, the element is
always deleted from the front position.
• Check whether the queue is Empty.
• If it is empty then display Queue is empty.
• If the queue is not empty, then get the last element and remove it from the queue.

101
Circular Queue

102
Types of Queue

TYPES OF QUEUES
1. Circular Queue 2. Deque 3. Priority Queue 4. Multiple Queue

Circular Queues
In linear queues, insertions can be done only at one end called the REAR and deletions are always done from the
other end called the FRONT.

Linear queue
Here, FRONT = and REAR = .

103
Types of Queue

• Now, if we want to insert another value, it will not be possible because the queue is completely full.
• There is no empty space where the value can be inserted.
• Consider a scenario in which two successive deletions are made.
• The queue will then be given as shown in Fig.

Queue after two successive deletions

Here, front = and REAR = .

104
Types of Queue

• Suppose we want to insert a new element in the queue shown in Fig..


• Even though there is space available, the overflow condition still exists because the condition rear = MAX – 1 still
holds true.
• This is a major drawback of a linear queue.

To resolve this problem, we have two solutions.


• First, shift the elements to the left so that the vacant space can be occupied and utilized efficiently. But this can
be very time-consuming, especially when the queue is quite large.

• The second option is to use a circular queue. In the circular queue, the first index comes right after the last index.

Circular queue

105
Types of Queue

For insertion, we now have to check for the following three conditions:

1. If front = 0 and rear = MAX – 1, then the circular queue is full.

Full queue

2. If rear != MAX – 1, then rear will be incremented and the value will be inserted as illustrated in Fig

Queue with vacant locations

106
Types of Queue

If front != 0 and rear = MAX – 1, then it means that the queue is not full.
So, set rear = 0 and insert the new element there, as shown in Fig.

Inserting an element in a circular queue

107
Types of Queue

Algorithm to insert an element in a circular queue

108
C Program to implement circular queue

109
C Program to implement circular queue

110
C Program to implement circular queue

111
C Program to implement circular queue

112
Algorithm to insert an element in a circular queue

113
Types of Queue

• In Step 1, we check for the overflow condition.


• In Step 2, we make two checks.
• First to see if the queue is empty, and second to see if the REAR end has already reached the maximum
capacity while there are certain free locations before the FRONT end.
• In Step 3, the value is stored in the queue at the location pointed by REAR.

114
Types of Queue

To delete an element, again we check for three conditions.


Fig. If front = –1, then there are no elements in the queue. So, an underflow condition will be reported.

Empty queue

If the queue is not empty and front = rear, then after deleting the element at the front the queue becomes empty
and so front and rear are set to –1. This is illustrated in Fig.

Queue with a single element

115
Types of Queue

If the queue is not empty and front = MAX–1, then after deleting the element at the front, front is set to 0. This is
shown in Fig.

Queue where front = MAX–1 before deletion

116
Types of Queue

• In Step 1, we check for the underflow condition.


• In Step 2, the value of the queue at the location pointed by FRONT is stored in VAL.
• In Step 3, we make two checks. First to see if the queue has become empty after deletion and second to see if
FRONT has reached the maximum capacity of the queue. The value of FRONT is then updated based on the
outcome of these checks

117
Types of Queue

Algorithm to delete an element from a circular queue

118
Types of Queue

Deques (Double ended queue)


• A deque (pronounced as ‘deck’ or ‘dequeue’) is a list in which the elements can be inserted or deleted at either
end.
• It is also known as a head-tail linked list because elements can be added to or removed from either the front
(head) or the back (tail) end.
• However, no element can be added and deleted from the middle.
• In a deque, two pointers are maintained, LEFT and RIGHT, which point to either end of the deque.
• The elements in a deque extend from the LEFT end to the RIGHT end and since it is circular, Dequeue[N–1] is
followed by Dequeue[0].
• Consider the deques shown in Fig.

Double-ended queues

119
Types of Queue

There are two variants of a double-ended queue


• Input restricted deque : In this dequeue, insertions can be done only at one of the ends, while deletions can be
done from both ends.
• Output restricted deque: In this dequeue, deletions can be done only at one of the ends, while insertions can be
done on both ends.

Some Practical Applications of Deque:


•Applied as both stack and queue, as it supports both operations.
•Storing a web browser’s history.
•Storing a software application’s list of undo operations.
•Job scheduling algorithm

120
Types of Queue

Deques have several other applications, some of which include:

•Palindrome checking: Deques can be used to check if a word or phrase is a palindrome. By inserting each
character of the word or phrase into a deque, it is possible to check if the word or phrase is a palindrome by
comparing the first and last characters, the second and second-to-last characters, and so on.

•Graph traversal: Deques can be used to implement Breadth-First Search (BFS) on a graph. BFS uses a queue to
keep track of the vertices to be visited next, and a deque can be used as an alternative to a queue in this case.

•Task scheduler: Deques can be used to implement a task scheduler that keeps track of tasks to be executed.
Tasks can be added to the back of the deque, and the scheduler can remove tasks from the front of the deque and
execute them.

121
Types of Queue

•Multi-level undo/redo functionality:


•Deques can be used to implement undo and redo functionality in applications.
•Each time a user performs an action, the current state of the application is pushed onto the deque.
•When the user undoes an action, the front of the deque is popped, and the previous state is restored.
•When the user redoes an action, the next state is popped from the deque.
•In computer science, deque can be used in many algorithms like LRU Cache, Round Robin Scheduling, Expression
Evaluation.

122
Types of Queue

Priority Queues
• A priority queue is a data structure in which each element is assigned a priority.
• The priority of the element will be used to determine the order in which the elements will be processed.
• The general rules of processing the elements of a priority queue are

➢ An element with higher priority is processed before an element with a lower priority.
➢ Two elements with the same priority are processed on a first-come-first-served (FCFS) basis.

• A priority queue can be thought of as a modified queue in which when an element has to be removed from the
queue, the one with the highest-priority is retrieved first.
• The priority of the element can be set based on various factors.
• Priority queues are widely used in operating systems to execute the highest priority process first.
• The priority of the process may be set based on the CPU time it requires to get executed completely.
• For example, if there are three processes, where the first process needs 5 ns to complete, the second process
needs 4 ns, and the third process needs 7 ns, then the second process will have the highest priority and will thus
be the first to be executed.

123
Types of Queue

• However, CPU time is not the only factor that determines the priority.
• Another factor is the importance of one process over another.
• In case we have to run two processes at the same time, where one process is concerned with online order
booking and the second with printing of stock details, then obviously the online booking is more important and
must be executed first.

How to Implement Priority Queue?


Priority queue can be implemented using the following data structures:
•Arrays
•Linked list
•Heap data structure
•Binary search tree

124
Types of Queue

Array Representation of a Priority Queue

125
Types of Queue

Properties of Priority Queue


A priority Queue is an extension of the queue with the following properties.

•Every item has a priority associated with it.


•An element with high priority is dequeued before an element with low priority.
•If two elements have the same priority, they are served according to their order in the queue.

126
Types of Queue

Operations of a Priority Queue:

1) Insertion in a Priority Queue


• When a new element is inserted in a priority queue, it moves to the empty slot from top to bottom and left to
right. However, if the element is not in the correct place then it will be compared with the parent node.
• If the element is not in the correct order, the elements are swapped.
• The swapping process continues until all the elements are placed in the correct position.

2) Deletion in a Priority Queue


• As you know that in a max heap, the maximum element is the root node.
• And it will remove the element which has maximum priority first.
• Thus, you remove the root node from the queue.
• This removal creates an empty slot, which will be further filled with new insertion.
• Then, it compares the newly inserted element with all the elements inside the queue to maintain the heap
invariant.

127
Types of Queue

3) Peek in a Priority Queue


This operation helps to return the maximum element from Max Heap or the minimum element from Min Heap
without deleting the node from the priority queue.

Types of Priority Queue:


1) Ascending Order Priority Queue
As the name suggests, in ascending order priority queue, the element with a lower priority value is given a higher
priority in the priority list.
For example, if we have the following elements in a priority queue arranged in ascending order like 4,6,8,9,10. Here,
4 is the smallest number, therefore, it will get the highest priority in a priority queue and so when we dequeue from
this type of priority queue, 4 will remove from the queue and dequeue returns 4.

128
Types of Queue

129
Types of Queue

2) Descending order Priority Queue


In descending order priority queue, a higher priority number is given as a higher priority in a priority.
For example, we take the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest
number, i.e., 5 is given as the highest priority in a priority queue.

130
Types of Queue

APPLICATIONs OF QUEUES
• Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
• Queues are used to transfer data between two processes (IO buffers), e.g., pipes, file IO, sockets.
• Queues are used as buffers on MP3 players and portable CD players, iPod playlist.
• Queues are used in Playlist for jukebox to add songs to the end, play from the front of the list.
• Queues are used in operating system for handling interrupts.
• When programming a real-time system that can be interrupted, for example, by a mouse click, it is necessary to
process the interrupts immediately, before proceeding with the current job.
• If the interrupts have to be handled in the order of arrival, then a FIFO queue is the appropriate data structure.

131
Types of Queue

132
Thank You

You might also like