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

Unit - II - Stack and Queue Stack

The document summarizes stacks and queues. It defines stacks as ordered collections where insertion and deletion occur at one end, following LIFO order. It describes stack operations like push, pop, peep and change. Queue types include simple, circular, and priority queues. Common applications of stacks and queues are also outlined. Algorithms for basic stack operations like push, pop, peep and change are provided in pseudocode. The document also discusses infix, postfix and prefix notation and provides an example of converting an infix expression to postfix form using a stack.

Uploaded by

Raj patel
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)
73 views

Unit - II - Stack and Queue Stack

The document summarizes stacks and queues. It defines stacks as ordered collections where insertion and deletion occur at one end, following LIFO order. It describes stack operations like push, pop, peep and change. Queue types include simple, circular, and priority queues. Common applications of stacks and queues are also outlined. Algorithms for basic stack operations like push, pop, peep and change are provided in pseudocode. The document also discusses infix, postfix and prefix notation and provides an example of converting an infix expression to postfix form using a stack.

Uploaded by

Raj patel
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/ 21

CVMU NVPAS B.Sc.

CA&IT – 4th Sem


Advanced Data & File Structure Unit 2 – Stack and Queue

Unit – II - Stack and Queue


Stack:
➢ Introduction
➢ Operations of the Stack- Push, Pop, Peep, Change
➢ Applications of the Stack: Infix, Postfix, Prefix Notation and Infix to
Postfix Conversion

Queues:
➢ Introduction
➢ Types of queues: Simple queues, Circular queues, Double ended queues,
Priority Queue
➢ Applications of Queue
➢ Operations of Simple Queue: Insert and Delete

----------------------------------------------------------------------------------------------------
Stack
Definition: A stack is an ordered collection of homogeneous data elements where the insertion
and deletion operation take place at one end only.

Characteristics of a Stack:
A stack data structure has following characteristics:
• It is non-primitive linear data structure.
• Its nature is LIFO (Last In First Out).
• The insertion and deletion operation occur only at one end.
• It is linear data structure of variable size.
• The elements are removed from the opposite order from that in which they are added to the
stack.
Operations on Stack:
Operation Description
1 Push • An insertion operation is known as Push.

Prepared By: Dr. MONIKA PATEL 1


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

• To insert an element on a stack.


2 Pop • A deletion operation is known as Pop.
• To delete an element from a stack.
3 Peep • To give the value of ith element from a stack.
4 Change • To change the value of ith element from a stack.

Top of a stack:
• The most accessible element of a stack is known as Top of a stack.
• The pointer at the top most position is called TOP.
• It is the most commonly accessible element of the stack. Insertion and deletion occur at
top.

Bottom of a stack
• The least accessible element of a stack is known as Bottom of a stack.
• The pointer at the last position is called BOTTOM.

Algorithms
[1]. An algorithm to insert an element into a stack.
PUSH (S, TOP, X, N): This procedure inserts an element X to the top of a stack which is
represented by a vector S containing N elements with a pointer Top denoting the position of the
top element in the stack.
Step 1: [ Check for Stack Overflow ]
If ( TOP >= N )
Then
Write (‘STACK OVERFLOW’)
Return
Step 2: [ Increment Top ]
TOP TOP + 1
Step 3: [ Insert an Element ]

Prepared By: Dr. MONIKA PATEL 2


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

S[ TOP ] X
Step 4: [ Finished ]
Return
[2]. An algorithm to delete an element from a stack.
POP (S, TOP): This function removes the top element from a stack which is represented by a
vector S and returns this element. Top is a pointer to the top element of the stack.
Step 1: [ Check for Underflow on Stack]
If ( TOP = 0 )
Then
Write (‘STACK UNDERFLOW ON POP’)
Take action in response to underflow
Exit
Step 2: [ Decrement pointer ]
TOP TOP - 1
Step 3: [ Return top Element of stack ]
Return ( S[ TOP + 1] )

[3]. An algorithm to give the value of ith element from a stack.


PEEP (S, TOP, N, I): Given a vector S (consisting of N elements) representing a sequentially
allocated stack and a pointer TOP denoting the top element of the stack, this function returns the
value of the ith element from the top of the stack. The element is not deleted by this function.
Step 1: [ Check for stack Underflow ]
If ( (TOP – I + 1) <= 0 )
Then
Write (‘STACK UNDERFLOW ON PEEP’)
Take action in response to underflow
Exit
Step 2: [ Return ith Element from top of stack]
Return ( S[ TOP - I + 1] )

Prepared By: Dr. MONIKA PATEL 3


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

[4]. An algorithm to change the value of ith element from a stack.


CHANGE (S, TOP, N, I, X): As before, a vector S (consisting of N elements) represents a
sequentially allocated stack and a pointer TOP denotes the top element of the stack. These
procedures change the value of the ith element from the top of the stack to the value contained in
X.
Step 1: [ Check for stack Underflow ]
If ( (TOP – I + 1) <= 0 )
Then
Write (‘STACK UNDERFLOW ON CHANGE’)
Return
Step 2: [ Change ith Element from top of stack ]
S[ TOP – I + 1] X
Step 3: [ Finished ]
Return

Applications of the Stack:


• Infix, Postfix, Prefix Notation
There are basically three types of notation for an expression (mathematical expression; An
expression is defined as a number of operands or data items combined using several operators.):
• Infix notation
• Prefix notation
• Postfix notation
Infix
• The infix notation is general mathematics, where the operator is written in-between the
operands.
• For example: The expression to add two numbers A and B is written in infix notation as:
A+B
• Thr operator '+' is written in-between the operands A and B. The reason why this notation
is called infix, is the place of operator in the expression.

Prepared By: Dr. MONIKA PATEL 4


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

Prefix
• A notation in which the operator is written before the operands is called Prefix notation.
• It is also called polish notation in the honor of the mathematician Jan Lukasiewicz who
developed this notation.
• Example: + AB
• As the operator '+' is written before the operands A and B, this notation is called prefix (pre
means before).
Postfix
• In the postfix notation the operators are written after the operands, so it is called the postfix
notation (post means after),
• It is also known as suffix notation or reverse polish notation.
• Example: AB +
• The prefix and postfix notations are not really as efficient to use as they might look at first.
• For example, a C function to return the sum of two variables A and B (passed as argument)
is called or invoked by the instruction: add (A, B)
• Note the operator add (name of the function) precedes the operands A and B.
• Because the postfix notation is a type of notation which is most suitable for a computer to
calculate any expression (due to its reversing characteristic), and is the universally accepted
notation for designing arithmetic and logical (ALU) unit of the CPU (processor). Therefore
it is necessary for us to study the postfix notation.
• Moreover the postfix notation is the way computer looks towards any arithmetic
expression, any expression entered into the computer is first converted into postfix
notation, stored in stack and then calculated.

Prepared By: Dr. MONIKA PATEL 5


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

Conversion: Infix to Postfix using manually and stack for parenthesis and
Non-parenthesis
Operator precedence
Exponential operator ^ Highest precedence

Multiplication / Division *, / Next, precedence

Addition / Subtraction +, - Least precedence

Converting infix expression to postfix form


A+B*C Infix Form

A+ (B * C) Parenthesized expression

A + (BC*) Convert the multiplication

A (BC*) + Convert the addition

ABC* + Postfix form

The rules to be remembered during infix to postfix conversion are:


1. Parenthesize the expression starting from left to right.
2. During parenthesizing the expression, the operands associated with operator having higher
precedence are first parenthesized. For example in above expression B * C is parenthesized
first before A + B.
3. The sub-expression (part of expression) which has been converted into postfix is to be treated
as single operand.
4. Once the expression is converted to postfix form remove the parenthesis.

EXAMPLE 1 Give postfix form for A + [ (B + C) + (D + E) * F ] / G


A + [ { (BC+) + (DE+) * F } / G ]

Prepared By: Dr. MONIKA PATEL 6


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

A + [ { (BC+) + (DE+ F*) } / G ]


SOLUTION Evaluation order is
A + [ { BC+ DE+ F* + } / G ]

A + (BC+ DE + F* + G /)

ABC + DE + F* + G / + Postfix Form

EXAMPLE 2 Give postfix form for A + B - C.


SOLUTION
(A + B) – C

(AB +) – C Now as said-after converting a part of expression to postfix, treat it as single


unit, therefore (AB+) now can be treated as T.

T–C

TC - Now as the final conversion is accomplished replace the value of T.

AB + C - Postfix Form

EXAMPLE 3 Convert the expression A * B + C / D to postfix form.


SOLUTION
In this particular example the * operator is encountered during left to right evaluation, which shares
an equal precedence to operator. When this happens (two operators with same precedence comes
in same expression), the operator that is encountered first while evaluating from left to right is first
parenthesized. Hence the above expression will be interpreted as:

(A * B) + C / D

(AB *) + C / D

Prepared By: Dr. MONIKA PATEL 7


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

(T) + C / D T = AB *

(T) + (C / D)

(T) + (CD /)

T+S S = CD /

TS +

AB * CD / Postfix expression

EXAMPLE 4 Give positive form for A * B + C


SOLUTION.
(A *B ) + C

(AB *) + C

(T) + C

TC +

AB * C+ Postfix expression

EXAMPLE 5 Give postfix form for A + B / C - D


SOLUTION
A + (B / C) – D

A + (BC / ) – D

A+T–D T = BC /

(A + T) – D

Prepared By: Dr. MONIKA PATEL 8


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

(AT +) – D

S–D S = AT +

SD -

AT + D -

ABC / + D - Postfix expression

EXAMPLE 6 Convert the expression (A + B) / (C - D) to postfix form.


SOLUTION In this expression the brackets are already specified. Therefore the conversion looks
like:

(AB+) / (CD-)

T/S Where T = (AB+) and S = (CD-)

TS /

AB+ CD- / Postfix expression

EXAMPLE 7 Give postfix form for (A + B) * C / D.


SOLUTION
(AB +) * C / D

T*C/D T = (AB+)

(T * C) / D

(TC *) / D

S/D S = (TC*)

Prepared By: Dr. MONIKA PATEL 9


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

SD /

TC * D /

AB + C * D / Postfix expression

EXAMPLE 8 Give postfix form for (A + B) * C / D + E ^ F / G


SOLUTION
(AB +) * C / D + E ^ F / G

T*C/D+(E^F)/G T = (AB +) and ^ has the highest priority

T * C / D + ( EF ^) / G

T*C/D+S/G S = (EF ^)

(T * C) / D + S / G

(TC *) / D + S / G

Q/D+S/G Q = (TC *)

(Q / D) + S / G

(QD /) + S / G

P+S/G P = (QD /)

P + (S / G)

P + (SG / )

P+O O = (SG /)

PO + Now we will expand the expression PO +

Prepared By: Dr. MONIKA PATEL 10


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

QD / O +

TC * D / O +

AB + C * D / S G / +

AB + C * D / EF ^ G / + Postfix expression

EXAMPLE 9 A + [ (B + C) + (D + E) * F] / G. Give postfix form.


SOLUTION
A + [ (BC+) + (DE+) * F ] / G

A+[T+S*F]/G where T = (BC+) and S = (DE+)

A + [ T + (S * F) ] / G

A + [ T + (SF*) ] / G

A+[T+Q]/G where Q = (SF*)

A + (TQ+) / G

A+P/G where P = (TQ+)

A + (PG /)

A+N where N = (PG/)

AN+ Expanding the expression AN+

A PG/ +

A TQ+ G/ +

A BC+ Q+ G/ +

Prepared By: Dr. MONIKA PATEL 11


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

A BC+ SF*+ G/ +

A BC+ DE+ F* +G/+ Postfix expression.

EXAMPLE 10 A + (B * C - (D / E ^ F) *G) *H. Give postfix form.


SOLUTION
A + ( B * C - ( D / (EF ^) ) * G ) *H (^ has the highest priority)

A+(B*C-(D/T)*G)*H T = EF ^

A + ( B * C - ( DT/ ) * G ) * H

A+(B*C-S*G)*H S = DT /

A + ( (B * C) - S * G ) *H

A + ( (BC *) – S * G ) * H

A+(Q–S*G)*H Q = (BC *)

A + ( Q – (S * G) ) * H

A + ( Q – (SG *) ) * H

A+(Q–P)*H P = (SG *)

A + ( QP - ) * H

A+O*H O = (QP - )

A+(O*H)

A + (OH *)

A+N N = (OH *)

Prepared By: Dr. MONIKA PATEL 12


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

AN + Expanding the expression AN+

A OH * +

A QP – H * +

A BC * P – H * +

A BC* SG * - H * +

A BC* DT/ G * - H * +

A BC* D EF^ / G * - H * + Postfix expression

EXAMPLE 11 A – B / (C * D ^ E). Give postfix form.


SOLUTION
A – B / (C * (D ^ E))

A – B / (C * (DE ^ ))

A – B / (C * T) T = (DE ^)

A – B / (CT *)

A–B/S S = (CT *)

A–(B/S)

A – ( BS / )

A–Q Q = (BS /)

AQ - Expanding the expression AQ -

A BS/ -

Prepared By: Dr. MONIKA PATEL 13


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

A B CT* / -

A B C DE^ * / - Postfix expression

Queue:
In ordinary English, a queue is defined as a waiting line, like a line of people waiting to purchase
tickets, where the first person in line is the first person served.
Real Life Examples:
1) A queue is a waiting line – seen in daily life
2) A line of people waiting for a bank teller
3) A line of cars at a toll booth
4) Patients waiting outside the doctor's clinic
• A queue is logically a First-In First-Out (FIFO) type of list.
• A queue is a non-primitive linear data structure.
• Definition: Queue is an ordered collection of homogeneous elements in which new elements
are added at one end called the REAR end, and the existing elements are deleted from
another end called the FRONT end.
• This linear data structure represents a linear list and permits deletion to be performed at one
end of the list and the insertion at the other.
• The information in such a list is processed in the same order as it was received.

Types of Queue
1) Simple Queue
2) Circular Queue
3) Priority Queue
4) Dequeue (Double Ended Queue)

Prepared By: Dr. MONIKA PATEL 14


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

Simple Queue
• Simple queue defines the simple operation of queue in which insertion occurs at the rear
(Tail) of the list and deletion occurs at the front (Head) of the list.

Algorithm for Insertion in Simple Queue


Procedure QINSERT(Q, F, R, N, Y). Given F and R, pointers to the front and rear elements of a
queue, a queue Q consisting of N elements, and an element Y, this procedure inserts Y at the rear
of the queue. Prior to the first invocation of the procedure, F and R have been set to zero.
Step 1 : [Overflow?]
If R ≥ N
then Write (‘OVERFLOW’)
Return
Step 2: [Increment rear pointer]
RR+1
Step 3: [Insert element]
Q[R]  Y
Step 4: [Is front pointer properly set?]
If F = 0
then F  1
Return

Algorithm for Deletion in Simple Queue


QDELETE(Q, F, R). Given F and R, the pointers to the front and rear elements of a queue,
respectively, and the queue Q to which they correspond, this function deletes and returns the last
element of the queue. Y is a temporary variable.

Prepared By: Dr. MONIKA PATEL 15


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

Step 1: [Underflow?]
If F = 0
then Write (‘UNDERFLOW’)
Return(0) (0 denotes an empty queue)
Step 2: [Delete element]
Y  Q[F]
Step 3:[Queue empty?]
If F = R
then FR0
else F  F +1
Step 4: [Return element]
Return(Y)

Disadvantages of Simple Queue


• In a Linear queue, once the queue is completely full, it's not possible to insert more elements
even if we remove some of the elements from a queue.
• For Example: Consider following queue

• When we remove an element from the queue, we are actually moving the front of the queue
forward, thereby reducing the overall size of the queue.
• And we cannot insert new elements, because the rear pointer is still at the end of the queue.

Prepared By: Dr. MONIKA PATEL 16


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

• The only way is to reset the linear queue, for a fresh start.
• This is the major limitation of a classical / simple queue, i.e. even if there is space available
at the front of the queue we cannot use it.

Circular Queue
• The basic limitation of simple queue can be solved by using Circular Queue.
• A circular queue is a linear data structure in which the operations are performed based on
FIFO (First In First Out) principle and the last position is connected back to the first position
to make a circle.
We can represent this circular queue as:

The following assumptions are made:

Fig. 1

1) Front will always be pointing to the first element (as in the linear queue)

Prepared By: Dr. MONIKA PATEL 17


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

2) If Front = Rear the queue will be empty


3) Each time a new element is inserted into the queue, the Rear is incremented by one.
Rear=Rear+1
4) Each time an element is deleted from the queue the value of Front is incremented by one.
Front=Front+1

Drawbacks of Circular Queue


• The drawback of circular queue is, difficult to distinguish the full and empty cases. It is also
known as boundary case problem.
• In circular queue it is necessary that:
1) Before insertion, fullness of Queue must be checked (for overflow).
2) Before deletion, emptiness of Queue must be checked (for underflow).

Double Ended Queues (Deque)


• It is a homogeneous linear list of elements in which insertion and deletion operations are
performed from both ends.
• We can insert elements from the rear end or from the front end.
• It is called double-ended queue.
• It is commonly referred to as deque.

• This general data class has some possible sub-types:


1) An input-restricted deque is one where deletion can be made from both ends, but
insertion can be made at one end only.

Prepared By: Dr. MONIKA PATEL 18


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

2) An output-restricted deque is one where insertion can be made at both ends, but
deletion can be made from one end only.
• Since both insertion and deletion are performed from either end, it is necessary to design an
algorithm to perform the following four operations:
1) Insertion of an element at the Rear end of the queue
2) Deletion of an element From the Front end of the queue
3) Insertion of an element at the Front end of the queue
4) Deletion of an element from the Rear end of the queue
• For an input-restricted deque only the operations specified in 1, 2, 3 and 4 are valid.
• For an output-restricted deque only the operations specified in 1, 2 and 3 are valid.

Priority Queue
• Priority Queue is more specialized data structure than Queue.
• Like ordinary queue, priority queue has same method but with a major difference.
• In Priority queue items are ordered by key value so that item with the lowest value of key is
at front and item with the highest value of key is at rear or vice versa.
• So we're assigned priority to item based on its key value.
• Lower the value, higher the priority.
• Priority Queue is an extension of queue with following properties.
A. Every item has a priority associated with it.
B. An element with high priority is dequeued before an element with low priority.
C. If two elements have the same priority, they are served according to their order in the
queue.
• Priority Queue is an extension of queue with following properties.
A. Every item has a priority associated with it.
B. An element with high priority is dequeued before an element with low priority.
C. If two elements have the same priority, they are served according to their order in the
queue.

Prepared By: Dr. MONIKA PATEL 19


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

Implementation of Priority Queue


• There can be two types of implementations of priority queue:
1) Ascending Priority Queue
2) Descending Priority Queue
• A collection of items into which items can be inserted arbitrarily and from which only the
smallest item can be removed is called Ascending Priority Queue.
• In Descending Priority Queue only the largest item is deleted.
• The elements of Priority Queue need not be numbers or characters that can be composed
directly.
• They may be complex structures that are ordered by one or several fields.
• Sometimes the field on which the element of a Priority Queue is ordered is not even part of
the elements themselves.
• The Priority Queue is a data structure in which intrinsic ordering of the elements determines
the result of its basic operations.
• An Ascending Priority Queue is a collection of items into which items can be inserted
arbitrarily and from which only the smallest item can be removed. On the other hand a
Descending Priority Queue allows only the largest item to be removed.
Operations
• Insertion: The insertion in Priority Queues is the same as in non-priority queues.

Prepared By: Dr. MONIKA PATEL 20


CVMU NVPAS B.Sc. CA&IT – 4th Sem
Advanced Data & File Structure Unit 2 – Stack and Queue

• Deletion: Deletion requires a search for the element of highest priority and deletes the
element with highest priority.
• The following methods can be used for deletion/removal from a given Priority Queue:
A. An empty indicator replaces deleted elements
B. After each deletion, elements can be moved up in the array decrementing the Rear
C. The array in the queue can be maintained as an ordered circular array

Applications of Queues
1) Round robin technique for processor scheduling is implemented using queues.
2) All types of customer services (like railway ticket reservation) center software are
designed using queues to store and service customers information.
3) Printer server routines are designed using queues. A number of users share a printer using
printer server

Difference between Simple/ Linear Queue vs. Circular Queue


Sr.
Linear Queue Circular Queue
No
1 The linear queue is an ordered list in Circular queue stores the data in the circular
which data elements are organized in fashion.
the sequential order.
2 Linear queue follows the FIFO order In the circular queue, the order of operations
for executing the task. performed on an element may change.
3 The insertion and deletion of the The circular queue is capable of inserting and
elements is fixed in linear queue i.e, deleting the element from any point until it is
addition from the rear end and deletion unoccupied.
from the front end.
4 Linear queue wastes the memory Circular queue makes the efficient use of
space. space.

Prepared By: Dr. MONIKA PATEL 21

You might also like