You are on page 1of 77

Unit - 2

Stacks & Queues


UNIT - 2
Stacks: Definition, Stack representation, Primitive operations on stack,
array representation of stacks.
Applications of stacks: Recursion, Fibonacci series, Tower of Hanoi
problem, Conversion of expressions, Evaluation of postfix expression,
Iteration v/s recursion
Queues: Definition, Queue representation, Primitive operations on
queue, array representation of queues, Circular queue, Priority queue,
Double ended queue, Applications of queues.
Stack
Stack
• A Stack is a linear data structure that follows
the LIFO (Last-In-First-Out) principle.
• Stack has one end, whereas the Queue has two ends
(front and rear).
• It contains only one pointer top pointer pointing to
the topmost element of the stack.
• Whenever an element is added in the stack, it is
added on the top of the stack, and the element can
be deleted only from the top of the stack.
• 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.
Standard Stack Operations
• The following are some common operations implemented on the
stack:
• push(): When we insert an element in a stack then the operation is
known as a push. If the stack is full then the overflow condition
occurs.
• pop(): When we delete an element from the stack, the operation is
known as a pop. If the stack is empty means that no element exists
in the stack, this state is known as an underflow state.
• isEmpty(): It determines whether the stack is empty or not.
• isFull(): It determines whether the stack is full or not.'
• peek(): It returns the element at the given position.
PUSH operation
• The steps involved in the PUSH operation is given
below:
• Before inserting an element in a stack, we check whether the
stack is full.
• If we try to insert the element in a stack, and the stack is full,
then the overflow condition occurs.
• When the new element is pushed in a stack, first, the value of
the top gets incremented, i.e., top=top+1 or top++, and the
element will be placed at the new position of the top.
• The elements will be inserted until we reach the max size of
the stack.
PUSH operation
Push - Algorithm
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 or top--.
POP operation
Pop - Algorithm
Display Operation
• All the stack element is called Display, if no element are presented in
the stack then appropriate error message has to be occur.

• Example top = 2
Display - Algorithm
Array Representation of Stacks

• A stack is a data structure that can be represented as an array. Let us


learn more about Array representation of a stack –
• An array is used to store an ordered list of elements. Using an array for
representation of stack is one of the easy techniques to manage the data.
But there is a major difference between an array and a stack.
• Size of an array is fixed.
• While, in a stack, there is no fixed size since the size of stack changed with
the number of elements inserted or deleted to and from it.
• Despite the difference, an array can be used to represent a stack by taking
an array of maximum size; big enough to manage a stack.
Array Representation of Stacks
Stack representation
• The following are maintained in array representation,
• An array S of default size. (which is >1)
• A variable top refers to the top element of stack.
• Array size
• S[6]=> 0 1 2 3 4 5
10 20 30

• Here, size is 6
• Top is value 30 i.e index 2.
• The variable top change from 0 to size-1
• Stack is empty when top = -1.
• Stack is full when top = size-1.
Applications of stacks
• Recursion,
• Fibonacci series,
• Tower of Hanoi problem,
• Conversion of expressions,
• Evaluation of postfix expression,
• Iteration v/s recursion
Recursion
• The recursion is a process by which a function calls itself. We use
recursion to solve bigger problem into smaller sub-problems. One
thing we have to keep in mind, that if each sub-problem is following
same kind of patterns, then only we can use the recursive
approach.
• A recursive function has two different parts. The base case and the
recursive case. The base case is used to terminate the task of
recurring. If base case is not defined, then the function will recur
infinite number of times.
• Types of recursion
• There are two type of recursion
1.Direct Recursion
2.Indirect Recursion
Direct Recursion:
• If a function recursively calls itself( means the same function) then it is called
direct recursion.
• //example of direct recursion

void directRecusrion()
{
// code....

directRecsion();

// code...
}
Indirect Recursion
• If a function call itself with the help of other function. Means a function func1 call
another function func2 which again calls func1 then it is indirect recursion.
• // example of indirect recursion
void indirectRecursion1()
{
// code...

indirectRecursion2();

// code...
}
void indirectRecursion2()
{
// code...

indirectRecursion1();

// code...
}
calculating factorial of a number.
n! = n * (n–1)!
Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
Recursive case of the factorial function will call itself but with a smaller value of n,
factorial(n) = n × factorial (n–1)
From the above example, let us analyze the steps of
a recursive program.

Step 1: Specify the base case which will stop the


function from making a call to itself.
Step 2: Check to see whether the current value
being processed matches with the value of the base
case. If yes, process and return the value.
Step 3: Divide the problem into smaller or simpler
sub-problems.
Step 4: Call the function from each sub-problem.
Step 5: Combine the results of the sub-problems.
Step 6: Return the result of the entire problem.
Fibonacci series
• Fibonacci Series generates subsequent number by adding
two previous numbers. Fibonacci series starts from two
numbers − F0 & F1.
• The initial values of F0 & F1 can be taken 0, 1.
• Let as see how to write a recursive definition of Fibonacci
Series.
Fibonacci series
algorithm Fibonacci series
Tower of Hanoi
• Tower of Hanoi, is a mathematical puzzle which consists of three
towers (pegs) and more than one rings is as depicted −

• These rings are of different sizes and stacked upon in an ascending


order, i.e. the smaller one sits over the larger one. There are other
variations of the puzzle where the number of disks increase, but the
tower count remains the same.
Concept
• There are three pegs say A, B and C.
• The different diameters of n discs are placed one above the other.
• Peg A is Source peg, Peg B is intermediate or temporary peg and peg
C is destination peg.
• The problem is to shift all discs from Peg A to Peg C by making
temporary Peg
• The rules to be followed while transferring the disc are:
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
The initial setup is

• After transferring all the disc to peg C from peg A,


https://www.tutorialspoint.com/
data_structures_algorithms/
tower_of_hanoi.htm
Algorithm for Tower of Hanoi can be driven as follows −

START
Procedure Hanoi(disk, source, dest, temp)

IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, temp, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, temp, dest, source) // Step 3
END IF

END Procedure
STOP
Conversion of expressions
• Expression:
• The sequence of operators and operands that reduce to a single value after
evaluation is called an expression.
• Eg: a + b, +ab, ab+
• Representation of expression: Three ways are there-
Infix Expression: operand operator operand
Example: A + B
Prefix Expression : operator operand operand
Example: +A B
Postfix Expression : operand operand operator
Example: A B +
Conversion of expressions
• Infix Notation
• We write expression in infix notation, e.g. a - b + c, where operators are
used in-between operands.
• Prefix Notation
• In this notation, operator is prefixed to operands, i.e. operator is written
ahead of operands. For example, +ab. This is equivalent to its infix
notation a + b. Prefix notation is also known as Polish Notation.
• Postfix Notation
• This notation style is known as Reversed Polish Notation. In this
notation style, the operator is postfixed to the operands i.e., the
operator is written after the operands. For example, ab+. This is
equivalent to its infix notation a + b.
following table briefly tries to show the
difference in all three notations
Sr.No. Infix Notation Prefix Notation Postfix Notation

1 a+b +ab ab+

2 (a + b) ∗ c ∗+abc ab+c∗

3 a ∗ (b + c) ∗a+bc abc+∗

4 a/b+c/d +/ab/cd ab/cd/+

5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
Precedence
Precedence
• When an operand is in between two different operators, which
operator will take the operand first, is decided by the
precedence of an operator over others.
• For example −

• As multiplication operation has precedence over addition,


• b * c will be evaluated first. A table of operator precedence is
provided later.
Associativity
Associativity
• Associativity describes the rule where operators with the same precedence
appear in an expression.
• For example, in expression a + b − c, both + and – have the same
precedence, then which part of the expression will be evaluated first, is
determined by associativity of those operators. Here, both + and − are left
associative, so the expression will be evaluated as (a + b) − c.
• Following is an operator precedence and associativity table (highest to lowest) −

Sr. No. Operator Precedence Associativity


1 Exponentiation ^ Highest Right Associative
2 Multiplication ( ∗ ) & Second Highest Left Associative
Division ( / )

3 Addition ( + ) & Lowest Left Associative


Subtraction ( − )
Conversion of infix to postfix
• Here, we will use the stack data structure for the conversion of infix
expression to prefix expression.
• Whenever an operator will encounter, we push operator into the stack.
If we encounter an operand, then we append the operand to the
expression.
Algorithm for the conversion from infix to
postfix expression
Convert the below infix expression to postfix
expression.
• A + (B * C – (D ^ E)) / F
nput Stack Postfix Expression
Let's understand through an example.
Expression
K K
+ +
• Infix expression:
L + K + L K- LM*N + (O^P) * W/U/V * T + Q
- - K L+
M - K L+ M
* -* K L+ M
N -* KL+MN
+ + KL+MN*
K L + M N* -
( +( K L + M N *-
O +( KL+MN*-O
^ +(^ K L + M N* - O
P +(^ K L + M N* - O P
) + K L + M N* - O P ^
* +* K L + M N* - O P ^
W +* K L + M N* - O P ^ W
/ +/ K L + M N* - O P ^ W *
U +/ K L + M N* - O P ^W*U
/ +/ K L + M N* - O P ^W*U/
V +/ KL + MN*-OP^W*U/V
* +* KL+MN*-OP^W*U/V/
Answer
• The final postfix expression of infix expression

• (K + L - M*N + (O^P) * W/U/V * T + Q)

is

• KL+MN*-OP^W*U/V/T*+Q+.
Evaluation of Arithmetic Expressions is based on the operator precedence and
associativity

 Brackets/paranthesis: ( )
 Exponentiation: ^
 Multiply, Divide & modulo division: * , /, and %
 Addition & subtraction: + and -

Convert the following infix expressions into Postfix expressions


1. (A–B) * (C+D)
Evaluation of postfix Expression
• The postfix expression is an expression in which the operator is
written after the operands. For example, the postfix expression of infix
notation ( 2+3) can be written as 2 3 +.
• Some key points regarding the postfix expression are:
• In postfix expression, operations are performed in the
order in which they have written from left to right.
• It does not require any parenthesis.
• We do not need to apply operator precedence rules and
associativity rules.
Point to remember to evaluate the postfix expression
• Scan the expression from left to right until we encounter any operator.
• Perform the operation
• Replace the expression with its computed value.
• Repeat the steps from 1 to 3 until no more operators exist.
Evaluation of postfix expression using stack.
Algorithm
Let's understand the evaluation of postfix expression using stack.

• Example 1: Postfix expression: 2 3 4 * +

Input Stack
234*+ empty Push 2
34*+ 2 Push 3
4*+ 32 Push 4
*+ 432 Pop 4 and 3, and perform 4*3 = 12. Push 12 into
the stack.

+ 12 2 Pop 12 and 2 from the stack, and perform 12+2 =


14. Push 14 into the stack.
Example 2: Postfix expression: 3 4 * 2 5 * +
Input Stack
34*25*+ empty Push 3
4*25*+ 3 Push 4
*2 5 * + 43 Pop 3 and 4 from the stack and perform 3*4 = 12. Push
12 into the stack.

25*+ 12 Push 2
5*+ 2 12 Push 5
*+ 5 2 12 Pop 5 and 2 from the stack and perform 5*2 = 10. Push
10 into the stack.

+ 10 12 Pop 10 and 12 from the stack and perform 10+12 = 22.


Push 22 into the stack.
Iteration v/s recursion
Property Recursion Iteration
A set of instructions repeatedly
Definition Function calls itself.
executed.

Application For functions. For loops.

Through base case, where there will When the termination condition for
Termination
be no function call. the iterator ceases to be satisfied.

Used when code size needs to be Used when time complexity needs
Usage small, and time complexity is not an to be balanced against an expanded
issue. code size.

Code Size Smaller code size Larger Code Size.

Very high(generally exponential) Relatively lower time


Time Complexity complexity(generally polynomial-
time complexity.
logarithmic).
Infix Expression to Prefix Expression
Infix Expression to Prefix Expression
Example - Infix Expression to Prefix Expression
Queue
Queues: Definition, Queue representation,
Primitive operations on queue, array
representation of queues, Circular queue,
Priority queue, Double ended queue,
Applications of queues.
Queues
• 1. A queue can be defined as an ordered list which
enables insert operations to be performed at one end
called REAR and delete operations to be performed at
another end called FRONT.
• 2. Queue is referred to be as First In First Out list.
Queues
Queue representations
• In 2 ways
• 1. Static representation (using Arrays)

• 2. Dynamic representation (using Linked lists)


The operations possible on queue are

• 1. Insert operation (adding element/ Enqueue)


• 2. Delete operation (removing element/ dequeue)
• 3. Display operation (display elements in queue)
Queue ADT
-----------------------------------------------
Domain:
Q[MAX], front, rear, item

Functions:
Enqueue() : adding new element
Dequeue() : removing an element
Display(): traversing
Types of Queue
• Linear queue or ordinary queue
• Circular queue,
• Double ended queue,
• Priority queue.
Linear queue or ordinary queue
• In linear queue, data is add at one end called rear end
deleted at other side called front end.

• Queue operations are:


• Insert operation (adding element/ Enqueue)
• Delete operation (removing element/ dequeue)
• Display operation (display elements in queue)
Insert operation
• The addition of new element to the queue is called insertion and
every time before inserting a new item rear is increment first then
item is inserted.
• The condition to be checked at the time of insertion is OVERFLOW.
• i.e where rear reaches maximum size.
Processing Insert operation
Delete operation
• The removal of front element from the queue is called deletion and
after deleting the element.
• check if the queue is empty
• for the first element, set the value of FRONT to 0
• increase the FRONT index by 1
• The condition to be checked in deletion is Queue underflow, i.e no item
is available in queue.
Delete operation
Delete operation - example
Display Operation
• Printing all the elements from the list.
Types of Queue
• Circular queue:
• Circular queue is a linear data structure. It follows FIFO
principle. In circular queue the last node is connected back to
the first node to make a circle. Circular linked list follow the
First In First Out principle. Elements are added at the rear end
and the elements are deleted at front end of the queue
Operations on Circular Queue
• Initiailly,
• Count = 0;
• F(front) = 0;
• R(rear) = -1;
• Max = 8;
• Display function
void display()
{
If (count == 0)
printf(“queue is empty);
else
{ printf(“queue is: “);
while(i != rear)
{
printf( “%d”, queue[i]);
i=(i+1) % Max;
}
Types of Queue
• Double ended queue:
• It is a homogeneous list of elements in which insertion
and deletion operations are performed from both the
ends. That is, we can insert elements from the rear end
or from the front ends. Hence it is called double ended
queue. It is commonly referred as deque.
Deque has 2 Types –
Input restricted deque
Output restricted deque
Types of Queue
• Priority queue:
• Here a priority is assigned to each element of the queue.
These priorities are considered at the time of processing the
elements. The elements having higher priority are processed
before that of lower priority.
• 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. 
Types of Queue
• Priority queue:
• Basic Operations
• insert / enqueue − add an item to the rear of the queue.
• remove / dequeue − remove an item from the front of the 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 asynchronously (data not necessarily
received at same rate as sent) 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 implementation of graph traversal algorithm (BFS).
• Queues are used in operating system for handling interrupts.
Applications of Queue:
• 1. Used in job scheduling algorithm.
• 2. Used in printers to store the requests made for
printing when the printer is busy.
• 3. It can be used to store data in first in first out format.
• 4. For CPU scheduling.

You might also like