SlideShare a Scribd company logo
UNIT 3
Queues & Stacks
Syllabus
• Queues: Introduction to Queues, Representation of Queues-
using Arrays and using Linked list, Implementation of Queues-
using Arrays and using Linked list, Application of Queues-
Circular Queues, Deques, Priority Queues, Multiple Queues.
• Stacks: Introduction to Stacks, Array Representation of Stacks,
Operations on Stacks, Linked list Representation of Stacks,
Operations on Linked Stack, Applications-Reversing list,
Factorial Calculation, Infix to Postfix Conversion, Evaluating
Postfix Expressions.
Introduction
• Queue is an important data structure which stores its elements in
an ordered manner.
• We can explain the concept of queues using the following analogy:
People moving on an escalator. The people who got on the escalator
first will be the first one to step out of it.
• A queue is a FIFO (First-In, First-Out) data structure in which the
element that is inserted first is the first one to be taken out.
• The elements in a queue are added at one end called the rear and
removed from the other one end called the front.
Array Representation of Queues
• Queues can be easily represented using linear arrays.
• Every queue has front and rear variables that point to the position
from where deletions and insertions can be done, respectively.
• Consider the queue shown in figure
0 1 2 3 4 5 6 7 8 9
12 9 7 18 14 36
• Here, front = 0 and rear = 5.
• If we want to add one more value in the list say with value 45, then
rear would be incremented by 1 and the value would be stored at
the position pointed by rear.
12 9 7 18 14 36 45
0 1 2 3 4 5 6 7 8 9
Array Representation of Queues
• Now, front = 0 and rear = 6. Every time a new element has to be
added, we will repeat the same procedure.
• Now, 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.
9 7 18 14 36 45
0 1 2 3 4 5 6 7 8 9
• Now, front = 1 and rear = 6.
Array Representation of Queues
• Before inserting an element in the queue we must check for
overflow conditions.
• An overflow occurs when we try to insert an element into a queue
that is already full, i.e. when rear = MAX – 1, where MAX specifies
the maximum number of elements that the queue can hold.
• Similarly, before deleting an element from the queue, we must
check for underflow condition.
• An underflow occurs when we try to delete an element from a
queue that is already empty. If front = -1 and rear = -1, this means
there is no element in the queue.
Algorithm for Insertion Operation
Algorithm to insert an element in a queue
Step 1: IF REAR=MAX-1, then;
Write OVERFLOW
Goto Step 4
[END OF IF]
Step 2: IF FRONT == -1 and REAR = -1, then
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: Exit
Algorithm for Deletion Operation
Algorithm to delete an element from a queue
Step 1: IF FRONT = -1 OR FRONT > REAR, then
Write UNDERFLOW
Goto Step 2
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: Exit
Linked Representation of Queues
• In a linked queue, every element has two parts: one that stores data
and the other that stores the address of the next element.
• The START pointer of the linked list is used as FRONT.
• 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.
1 7 3 4 2 6 5 X
FRONT REAR
Inserting an Element in a Linked Queue
Algorithm to insert an element in a linked queue
Step 1: Allocate memory for the new node and name it as PTR
Step 2: SET PTR->DATA = VAL
Step 3: IF FRONT = NULL, then
SET FRONT = REAR = PTR
SET FRONT->NEXT = REAR->NEXT = NULL
ELSE
SET REAR->NEXT = PTR
SET REAR = PTR
SET REAR->NEXT = NULL
[END OF IF]
Step 4: END
Deleting an Element from a Linked
Queue
Algorithm to delete an element from a linked queue
Step 1: IF FRONT = NULL, then
Write “Underflow”
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: FRONT = FRONT->NEXT
Step 4: FREE PTR
Step 5: END
Circular Queues
7 18 14 36 45 21 99 72
0 1 2 3 4 5 6 7 8 9
• We will explain the concept of circular queues using an example.
• In this queue, front = 2 and rear = 9.
• Now, if you want to insert a new element, it cannot be done
because the space is available only at the left of the queue.
• If rear = MAX – 1, then OVERFLOW condition exists.
• This is the major drawback of a linear queue. Even if space is
available, no insertions can be done once rear is equal to MAX – 1.
• This leads to wastage of space. In order to overcome this problem,
we use circular queues.
• In a circular queue, the first index comes right after the last index.
• A circular queue is full, only when front=0 and rear = Max – 1.
Inserting an Element in a Circular
Queue
• For insertion we check for three conditions which are as follows:
 If front=0 and rear= MAX – 1, then the circular queue is full.
90 49 7 18 14 36 45 21 99 72
front=0 1 2 3 4 5 6 7 8 rear = 9
 If rear != MAX – 1, then the rear will be incremented and value will
be inserted
90 49 7 18 14 36 45 21 99
front=0 1 2 3 4 5 6 7 rear= 8 9
• 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.
49 7 18 14 36 45 21 99 72
front=1 2 3 4 5 6 7 8 rear= 9
Algorithm to Insert an Element in a
Circular Queue
Step 1: IF FRONT = 0 and Rear = MAX – 1, then
Write “OVERFLOW”
Goto Step 4
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1, then;
SET FRONT = REAR = 0
ELSE IF REAR = MAX – 1 and FRONT != 0
SET REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: Exit
Deleting an Element from a Circular
Queue
• To delete an element again we will check for three conditions:
 If front = -1, then it means there are no elements in the queue. So
an underflow condition will be reported.
0 1 2 3 4 5 6 7 8 9
 If the queue is not empty and after returning the value on front, if
front = rear, then it means now the queue has become empty and
so front and rear are set to -1.
Delete this element and set
rear = front = -1
81
0 1 2 3 4 5 6 7 8 front=rear= 9
 If the queue is not empty and after returning the value on front, if
front = MAX -1, then front is set to 0.
72 63 9 18 27 39 81
0 1 2 3 4 rear= 5 6 7 8 front= 9
Algorithm to Delete an Element from a Circular Queue
Step 1: IF FRONT = -1, then
Write “Underflow”
Goto Step 4
[END OF IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END OF IF]
[END OF IF]
Step 4: EXIT
Deques
• A deque is a list in which 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 the front (head) or back (tail).
• A deque can be implemented either using a circular array or a
circular doubly linked list.
• In a deque, two pointers are maintained, LEFT and RIGHT which
point to either end of the deque.
• The elements in a deque stretch from LEFT end to the RIGHT and
since it is circular, Dequeue[N-1] is followed by Dequeue[0].
Deques
• 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 the
ends.
Output restricted deque: In this dequeue deletions can be done
only at one of the ends while insertions can be done on both the
ends.
29 37 45 54 63
0 1 2 LEFT = 3 4 5 6 RIGHT = 7 8
9
42
63 27 18
RIGHT = 0 1 2 3 4 5 6 LEFT = 7 8 9
Priority Queues
• A priority queue is a queue in which each element is assigned a
priority.
• The priority of elements is used to determine the order in which
these elements will be processed.
• The general rule of processing elements of a priority queue can be
given as:
An element with higher priority is processed before an element
with lower priority
Two elements with same priority are processed on a first come
first served (FCFS) basis
• Priority queues are widely used in operating systems to execute the
highest priority process first.
• In computer’s memory priority queues can be represented using
arrays or linked lists.
Linked Representation of Priority
Queues
• When a priority queue is implemented using a linked list, then
every node of the list contains three parts: (1) the information or
data part, (ii) the priority number of the element, (iii) and address
of the next element.
• If we are using a sorted linked list, then element having higher
priority will precede the element with lower priority.
A 1 B 2 C 3 D 3 E 4 X
A 1 B 2 C 3 F 4 D 5 E 6 X
Priority queue after insertion of a new node
Array Representation of Priority
Queues
• When arrays are used to implement a priority queue, then a
separate queue for each priority number is maintained.
• Each of these queues will be implemented using circular arrays
or circular queues. Every individual queue will have its own
FRONT and REAR pointers.
• We can use a two-dimensional array for this purpose where
each queue will be allocated same amount of space.
• Given the front and rear values of each queue, a two
dimensional matrix can be formed.
Multiple Queues
• When implementing a queue using an array, the size of the array
must be known in advance.
• If the queue 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, but this results in sheer wastage
of memory. Thus, there lies a tradeoff between the frequency of
overflows and the space allocated.
• A better solution to deal with this problem is to have multiple
queues or to have more than one queue in the same array.
• One important point to note is that while queue A will grow from left
to right, the queue B on the same time will grow from right to left.
Queue A Queue B
0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1
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 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 OS for handling interrupts. When programming a
real-time system that can be interrupted, for ex, 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
© Oxford University Press 2014. All rights reserved.
Stacks
© Oxford University Press 2014. All rights reserved.
Introduction
• Stack is an important data structure which stores its elements in
an ordered manner.
• Take an analogy of a pile of plates where one plate is placed on
top of the other. A plate can be removed only from the topmost
position. Hence, you can add and remove the plate only at/from
one position, that is, the topmost position.
The topmost plate will
be removed first
Another plate will
be added on top of
this plate
© Oxford University Press 2014. All rights reserved.
Stacks
• 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 is inserted last is the first one to be taken out.
• Stacks can be implemented either using an array or a linked list.
© Oxford University Press 2014. All rights reserved.
Array Representation of Stacks
• In computer’s memory stacks can be represented as a linear array.
• Every stack has a variable TOP associated with it.
• TOP is used to store the address of the topmost element of the
stack. It is this position from where the element will be added or
deleted.
• There is another variable MAX which will be 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.
© Oxford University Press 2014. All rights reserved.
Push Operation
• The push operation is used to insert an element in to 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 this is the case then it means the stack is
full and no more insertions can further be done.
• If an attempt is made to insert a value in a stack that is already full,
an OVERFLOW message is printed.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D E F
0 1 2 3 4 TOP =5 6 7 8 9
© Oxford University Press 2014. All rights reserved.
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 this is the case then it means the stack is
empty so no more deletions can further be done.
• If an attempt is made to delete a value from a stack that is already
empty, an UNDERFLOW message is printed.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D
0 1 2 TOP = 3 4 5 6 7
8 9
© Oxford University Press 2014. All rights reserved.
Peek Operation
• Peek is an operation that returns the value of the topmost
element of the stack without deleting it from the stack.
• However, the peep operation first checks if the stack is empty or
contains some elements.
• If TOP = NULL, then an appropriate message is printed else the
value is returned.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
Here Peep operation will return E, as it is the value of the
topmost element of the stack.
© Oxford University Press 2014. All rights reserved.
Algorithms for Push and Pop
Operations
Algorithm to PUSH an element in a stack
Step 1: IF TOP = MAX-1, then
PRINT “OVERFLOW”
Goto Step 4
[END OF IF]
Step 2: SET TOP = TOP + 1
Step 3: SET STACK[TOP] = VALUE
Step 4: END
Algorithm to POP an element from a stack
Step 1: IF TOP = NULL, then
PRINT “UNDERFLOW”
Goto Step 4
[END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP - 1
Step 4: END
© Oxford University Press 2014. All rights reserved.
Algorithm for Peep Operation
Algorithm for Peep Operation
Step 1: IF TOP =NULL, then
PRINT “STACK IS EMPTY”
Go TO Step 3
[END OF IF]
Step 2: RETURN STACK[TOP]
Step 3: END
© Oxford University Press 2014. All rights reserved.
Linear Representation of Stacks
• 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.
• If TOP is NULL then it indicates that the stack is empty.
1 7 3 4 2 6 5 X
TOP
© Oxford University Press 2014. All rights reserved.
Push Operation on a Linked Stack
Algorithm to PUSH an element in a linked stack
Step 1: Allocate memory for the new node and name it as New_Node
Step 2: SET New_Node->DATA = VAL
Step 3: IF TOP = NULL, then
SET New_Node->NEXT = NULL
SET TOP = New_Node
ELSE
SET New_node->NEXT = TOP
SET TOP = New_Node
[END OF IF]
Step 4: END
1 7 3 4 2 6 5 X
TOP
9 1 7 3 4 2 6 5 X
TOP
© Oxford University Press 2014. All rights reserved.
Pop Operation on a Linked Stack
Algorithm to POP an element from a stack
Step 1: IF TOP = NULL, then
PRINT “UNDERFLOW”
Goto Step 5
[END OF IF]
Step 2: SET PTR = TOP
Step 3: SET TOP = TOP ->NEXT
Step 4: FREE PTR
Step 5: END
9 1 7 3 4 2 6 5 X
TOP
1 7 3 4 2 6 5 X
TOP
© Oxford University Press 2014. All rights reserved.
Multiple Stacks
• When we implemented a stack using an array, we had seen that
the size of the array must be known in advance.
• If the stack is allocated less space, then frequent OVERFLOW
conditions will be encountered.
• In case, we allocate a large amount of space for the stack, it will
result in sheer wastage of memory. Thus, there lies a tradeoff
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.
Stack A Stack B
0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1
© Oxford University Press 2014. All rights reserved.
Applications of Stacks
• 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 postfix expression
• Recursion
• Tower of Hanoi
© Oxford University Press 2014. All rights reserved.
Infix Notation
• Infix, Postfix and Prefix notations are three different but equivalent
notations of writing algebraic expressions.
• While writing an arithmetic expression using infix notation, the
operator is placed between the operands. For example, A+B; here,
plus operator is placed between the two operands A and B.
• Although it is easy to write expressions using infix notation,
computers find it difficult to parse as they need a lot of information
to evaluate the expression.
• Information is needed about operator precedence, associativity
rules, and brackets which overrides these rules.
• So, computers work more efficiently with expressions written using
prefix and postfix notations.
© Oxford University Press 2014. All rights reserved.
Postfix Notation
• Postfix notation was given by Jan Łukasiewicz who was a Polish
logician, mathematician, and philosopher. His aim was to develop
a parenthesis-free prefix notation (also known as Polish notation)
and a postfix notation which is better known as Reverse Polish
Notation or RPN.
• In postfix notation, the operator is placed after the operands. For
example, if an expression is written as A+B in infix notation, the
same expression can be written as AB+ in postfix notation.
• The order of evaluation of a postfix expression is always from left
to right.
© Oxford University Press 2014. All rights reserved.
Postfix Notation
• The expression (A + B) * C is written as:
AB+C* in the postfix notation.
• A postfix operation does not even follow the rules of operator
precedence. The operator which occurs first in the expression is
operated first on the operands.
• For example, given a postfix notation AB+C*. While evaluation,
addition will be performed prior to multiplication.
© Oxford University Press 2014. All rights reserved.
Prefix Notation
• In a prefix notation, the operator is placed before the operands.
• For example, if A+B is an expression in infix notation, then the
corresponding expression in prefix notation is given by +AB.
• While evaluating a prefix expression, the operators are applied to
the operands that are present immediately on the right of the
operator.
• Prefix expressions also do not follow the rules of operator
precedence, associativity, and even brackets cannot alter the
order of evaluation.
• The expression (A + B) * C is written as:
*+ABC in the prefix notation
© Oxford University Press 2014. All rights reserved.
Evaluation of an Infix Expression
Algorithm to convert an Infix notation into postfix notation
Step 1: Add ‘)” to the end of the infix expression
Step 2: Push “(“ on to the stack
Step 3: Repeat until each character in the infix notation is scanned
IF a “(“ is encountered, push it on the stack
IF an operand (whether a digit or an alphabet) is
encountered,
add it to the postfix expression.
IF a “)” is encountered, then;
a . Repeatedly pop from stack and add it to the postfix expression
until a “(” is encountered.
b. Discard the “(“. That is, remove the “(“ from stack and do not
add it to the postfix expression
IF an operator X is encountered, then;
a Repeatedly pop from stack and add each operator (popped from the
stack) to the postfix expression which has the same precedence or
a higher precedence than X
b. Push the operator X to the stack
Step 4: Repeatedly pop from the stack and add it to the postfix expression
until the stack is empty
Step 5: EXIT
STEP 1: Convert the infix expression into its equivalent postfix expression
© Oxford University Press 2014. All rights reserved.
Evaluation of an Infix Expression
STEP 2: Evaluate the postfix expression
Algorithm to evaluate a postfix expression
Step 1: Add a “)” at the end of the postfix expression
Step 2: Scan every character of the postfix expression and repeat
steps 3 and 4 until “)”is encountered
Step 3: IF an operand is encountered, push it on the stack
IF an operator X is encountered, then
a. pop the top two elements from the stack as A and B
b. Evaluate B X A, where A was the topmost element
and B was
the element below A.
c. Push the result of evaluation on the stack
[END OF IF]
Step 4: SET RESULT equal to the topmost element of the stack
Step 5: EXIT
© Oxford University Press 2014. All rights reserved.
Evaluation of an Infix Expression
• Let us now take an example that makes use of this algorithm.
• Consider the infix expression given as “9 - (( 3 * 4) + 8) / 4”.
• The infix expression "9 - (( 3 * 4) + 8) / 4" can be written as “9 3 4 * 8
+ 4 / -“ using postfix notation.
• Look at table which shows the procedure.
Character scanned Stack
9 9
3 9, 3
4 9, 3, 4
* 9, 12
8 9, 12, 8
+ 9, 20
4 9, 20, 4
/ 9, 5
- 4
© Oxford University Press 2014. All rights reserved.
Convert Infix Expression into Prefix
Expression
Consider an infix expression: (A – B / C) * (A / K – L)
• Step 1: Reverse the infix string. Note that while reversing the string
you must interchange left and right parenthesis.
(L – K / A) * (C / B – A)
• Step 2: Obtain the corresponding postfix expression of the infix
expression obtained as a result of Step 1.
• The expression is: (L – K / A) * (C / B – A)
• Therefore, [L – (K A /)] * [ (C B /) - A ]
= [LKA/-] * [ CB/A-]
= L K A / - C B / A - *
• Step 3: Reverse the postfix expression to get the prefix expression
• Therefore, the prefix expression is * - A / B C - / A K L
© Oxford University Press 2014. All rights reserved.
Recursion
• Recursion is an implicit application of STACK ADT.
• A recursive function is a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a
call to itself.
• Every recursive solution has two major cases: the base case in
which the problem is simple enough to be solved directly without
making any further calls to the same function.
• Recursive case, in which first the problem at hand is divided into
simpler subparts. Second the function calls itself but with subparts
of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
© Oxford University Press 2014. All rights reserved.
Types of Recursion
• Any recursive function can be characterized based on:
 whether the function calls itself directly or indirectly (direct or
indirect recursion).
 whether any operation is pending at each recursive call (tail-
recursive or not).
 the structure of the calling pattern (linear or tree-recursive).
Recursion
Direct Indirect Linear Tree Tail
© Oxford University Press 2014. All rights reserved.
Direct Recursion
• A function is said to be directly recursive if it explicitly calls itself.
• For example, consider the function given below.
int Func( int n)
{
if(n==0)
retrun n;
return (Func(n-1));
}
© Oxford University Press 2014. All rights reserved.
Indirect Recursion
• A function is said to be indirectly recursive if it contains a call to
another function which ultimately calls it.
• Look at the functions given below. These two functions are
indirectly recursive as they both call each other.
int Func1(int n)
{
if(n==0)
return n;
return Func2(n);
}
int Func2(int x)
{
return Func1(x-1);
}
© Oxford University Press 2014. All rights reserved.
Linear Recursion
• Recursive functions can also be characterized depending on the
way in which the recursion grows: in a linear fashion or forming a
tree structure.
• In simple words, a recursive function is said to be linearly recursive
when no pending operation involves another recursive call to the
function.
• For example, the factorial function is linearly recursive as the
pending operation involves only multiplication to be performed
and does not involve another call to fact() function.
© Oxford University Press 2014. All rights reserved.
Tree Recursion
• A recursive function is said to be tree recursive (or non-linearly
recursive) if the pending operation makes another recursive call to
the function.
• For example, the Fibonacci function Fib in which the pending
operations recursively calls the Fib function.
int Fibonacci(int num)
{
if(num <= 2)
return 1;
return ( Fibonacci (num - 1) + Fibonacci(num – 2));
}
© Oxford University Press 2014. All rights reserved.
Tail Recursion
• A recursive function is said to be tail recursive if no operations are
pending to be performed when the recursive function returns to its
caller.
• That is, when the called function returns, the returned value is
immediately returned from the calling function.
• Tail recursive functions are highly desirable because they are much
more efficient to use as in their case, the amount of information
that has to be stored on the system stack is independent of the
number of recursive calls.
int Fact(n)
{
return Fact1(n, 1);
}
int Fact1(int n, int res)
{
if (n==1)
return res;
return Fact1(n-1, n*res);
}
© Oxford University Press 2014. All rights reserved.
Fibonacci Series
• The Fibonacci series can be given as:
0 1 1 2 3 5 8 13 21 34 55……
• That is, the third term of the series is the sum of the first and
second terms. Similarly, fourth term is the sum of second and third
terms, so on and so forth.
• A recursive solution to find the nth term of the Fibonacci series can
be given as:
FIB(n) = 1, if n<=2
FIB (n - 1) + FIB (n - 2), otherwise FIB(7)
FIB(6) FIB(5)
FIB(5) FIB(4) FIB(4)
FIB(4) FIB(3) FIB(3) FIB(2) FIB(3) FIB(2) FIB(2) FIB(1)
FIB(3) FIB(2)
FIB(2) FIB(1)
FIB(2) FIB(1) FIB(2) FIB(1)
FIB(2) FIB(1)
FIB(3)
© Oxford University Press 2014. All rights reserved.
Pros and Cons of Recursion
Pros
• Recursive solutions often tend to be shorter and simpler than non-
recursive ones.
• Code is clearer and easier to use.
• Follows a divide and conquer technique to solve problems.
• In some (limited) instances, recursion may be more efficient.
Cons
• For some programmers and readers, recursion is a difficult
concept.
• Recursion is implemented using system stack. If the stack space on
the system is limited, recursion to a deeper level will be difficult to
implement.
• Aborting a recursive process in midstream is slow.
• Using a recursive function takes more memory and time to execute
as compared to its non-recursive counterpart.
• It is difficult to find bugs, particularly when using global variables.
© Oxford University Press 2014. All rights reserved.
Tower of Hanoi
Tower of Hanoi is one of the main applications of a recursion. It says, "if you can solve
n-1 cases, then you can easily solve the nth case"
A B C A B C
If there is only one ring, then simply move the ring from source to the destination
B
A B C A C
A B C
If there are two rings, then first move ring 1 to the
spare pole and then move ring 2 from source to the
destination. Finally move ring 1 from the source to the
destination
A B C
© Oxford University Press 2014. All rights reserved.
Tower of Hanoi
Consider the working with three rings.
A B C
A B C
A B C
A B C
A B C A B C
A B C A B C

More Related Content

PPT
10994103.ppt
PPT
cp264_lecture18_queue.ppt
PPTX
RPT_02_B_Queue presentation for FE students
PPTX
queue & its applications
PPTX
apllicationsof queffffffffffffffffffffffffffffue.pptx
PPTX
Queue in Data Structure
PPTX
queue_final.pptx
PPTX
fdfdfdsfadsfsfdsfsffggfdgdgreddsfewdcedrdfe
10994103.ppt
cp264_lecture18_queue.ppt
RPT_02_B_Queue presentation for FE students
queue & its applications
apllicationsof queffffffffffffffffffffffffffffue.pptx
Queue in Data Structure
queue_final.pptx
fdfdfdsfadsfsfdsfsffggfdgdgreddsfewdcedrdfe

Similar to Stacks and Queues concept in Data Structures (20)

PPTX
Detalied information of queue
PPTX
Lecture 7 data structures and algorithms
PDF
LEC4-DS ALGO.pdf
PPT
Lecture three of datat structures ,.The Queue-ds.ppt
PPTX
PPTX
Queue - Data Structure - Notes
PPTX
6.queue
PPT
Data structure.ppt
PPT
intr_qyyuujjjjjjjkkkkkkkkkkkkkjkueue.ppt
PPTX
queue.pptx
PPTX
Queue
PPT
Queues.ppt
PPTX
08_Queues.pptx showing how que works given vertex
PPTX
4. Queues in Data Structure
PPT
queue (1).ppt queue notes and ppt in Data Structures
PPTX
Stack and Queue.pptx
Detalied information of queue
Lecture 7 data structures and algorithms
LEC4-DS ALGO.pdf
Lecture three of datat structures ,.The Queue-ds.ppt
Queue - Data Structure - Notes
6.queue
Data structure.ppt
intr_qyyuujjjjjjjkkkkkkkkkkkkkjkueue.ppt
queue.pptx
Queue
Queues.ppt
08_Queues.pptx showing how que works given vertex
4. Queues in Data Structure
queue (1).ppt queue notes and ppt in Data Structures
Stack and Queue.pptx
Ad

Recently uploaded (20)

PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Sustainable Sites - Green Building Construction
PPTX
web development for engineering and engineering
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Well-logging-methods_new................
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
additive manufacturing of ss316l using mig welding
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Construction Project Organization Group 2.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
PPT on Performance Review to get promotions
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
composite construction of structures.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Sustainable Sites - Green Building Construction
web development for engineering and engineering
bas. eng. economics group 4 presentation 1.pptx
Well-logging-methods_new................
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
additive manufacturing of ss316l using mig welding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Construction Project Organization Group 2.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPT on Performance Review to get promotions
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
composite construction of structures.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
CH1 Production IntroductoryConcepts.pptx
Ad

Stacks and Queues concept in Data Structures

  • 2. Syllabus • Queues: Introduction to Queues, Representation of Queues- using Arrays and using Linked list, Implementation of Queues- using Arrays and using Linked list, Application of Queues- Circular Queues, Deques, Priority Queues, Multiple Queues. • Stacks: Introduction to Stacks, Array Representation of Stacks, Operations on Stacks, Linked list Representation of Stacks, Operations on Linked Stack, Applications-Reversing list, Factorial Calculation, Infix to Postfix Conversion, Evaluating Postfix Expressions.
  • 3. Introduction • Queue is an important data structure which stores its elements in an ordered manner. • We can explain the concept of queues using the following analogy: People moving on an escalator. The people who got on the escalator first will be the first one to step out of it. • A queue is a FIFO (First-In, First-Out) data structure in which the element that is inserted first is the first one to be taken out. • The elements in a queue are added at one end called the rear and removed from the other one end called the front.
  • 4. Array Representation of Queues • Queues can be easily represented using linear arrays. • Every queue has front and rear variables that point to the position from where deletions and insertions can be done, respectively. • Consider the queue shown in figure 0 1 2 3 4 5 6 7 8 9 12 9 7 18 14 36 • Here, front = 0 and rear = 5. • If we want to add one more value in the list say with value 45, then rear would be incremented by 1 and the value would be stored at the position pointed by rear. 12 9 7 18 14 36 45 0 1 2 3 4 5 6 7 8 9
  • 5. Array Representation of Queues • Now, front = 0 and rear = 6. Every time a new element has to be added, we will repeat the same procedure. • Now, 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. 9 7 18 14 36 45 0 1 2 3 4 5 6 7 8 9 • Now, front = 1 and rear = 6.
  • 6. Array Representation of Queues • Before inserting an element in the queue we must check for overflow conditions. • An overflow occurs when we try to insert an element into a queue that is already full, i.e. when rear = MAX – 1, where MAX specifies the maximum number of elements that the queue can hold. • Similarly, before deleting an element from the queue, we must check for underflow condition. • An underflow occurs when we try to delete an element from a queue that is already empty. If front = -1 and rear = -1, this means there is no element in the queue.
  • 7. Algorithm for Insertion Operation Algorithm to insert an element in a queue Step 1: IF REAR=MAX-1, then; Write OVERFLOW Goto Step 4 [END OF IF] Step 2: IF FRONT == -1 and REAR = -1, then SET FRONT = REAR = 0 ELSE SET REAR = REAR + 1 [END OF IF] Step 3: SET QUEUE[REAR] = NUM Step 4: Exit
  • 8. Algorithm for Deletion Operation Algorithm to delete an element from a queue Step 1: IF FRONT = -1 OR FRONT > REAR, then Write UNDERFLOW Goto Step 2 ELSE SET VAL = QUEUE[FRONT] SET FRONT = FRONT + 1 [END OF IF] Step 2: Exit
  • 9. Linked Representation of Queues • In a linked queue, every element has two parts: one that stores data and the other that stores the address of the next element. • The START pointer of the linked list is used as FRONT. • 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. 1 7 3 4 2 6 5 X FRONT REAR
  • 10. Inserting an Element in a Linked Queue Algorithm to insert an element in a linked queue Step 1: Allocate memory for the new node and name it as PTR Step 2: SET PTR->DATA = VAL Step 3: IF FRONT = NULL, then SET FRONT = REAR = PTR SET FRONT->NEXT = REAR->NEXT = NULL ELSE SET REAR->NEXT = PTR SET REAR = PTR SET REAR->NEXT = NULL [END OF IF] Step 4: END
  • 11. Deleting an Element from a Linked Queue Algorithm to delete an element from a linked queue Step 1: IF FRONT = NULL, then Write “Underflow” Go to Step 5 [END OF IF] Step 2: SET PTR = FRONT Step 3: FRONT = FRONT->NEXT Step 4: FREE PTR Step 5: END
  • 12. Circular Queues 7 18 14 36 45 21 99 72 0 1 2 3 4 5 6 7 8 9 • We will explain the concept of circular queues using an example. • In this queue, front = 2 and rear = 9. • Now, if you want to insert a new element, it cannot be done because the space is available only at the left of the queue. • If rear = MAX – 1, then OVERFLOW condition exists. • This is the major drawback of a linear queue. Even if space is available, no insertions can be done once rear is equal to MAX – 1. • This leads to wastage of space. In order to overcome this problem, we use circular queues. • In a circular queue, the first index comes right after the last index. • A circular queue is full, only when front=0 and rear = Max – 1.
  • 13. Inserting an Element in a Circular Queue • For insertion we check for three conditions which are as follows:  If front=0 and rear= MAX – 1, then the circular queue is full. 90 49 7 18 14 36 45 21 99 72 front=0 1 2 3 4 5 6 7 8 rear = 9  If rear != MAX – 1, then the rear will be incremented and value will be inserted 90 49 7 18 14 36 45 21 99 front=0 1 2 3 4 5 6 7 rear= 8 9 • 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. 49 7 18 14 36 45 21 99 72 front=1 2 3 4 5 6 7 8 rear= 9
  • 14. Algorithm to Insert an Element in a Circular Queue Step 1: IF FRONT = 0 and Rear = MAX – 1, then Write “OVERFLOW” Goto Step 4 [END OF IF] Step 2: IF FRONT = -1 and REAR = -1, then; SET FRONT = REAR = 0 ELSE IF REAR = MAX – 1 and FRONT != 0 SET REAR = 0 ELSE SET REAR = REAR + 1 [END OF IF] Step 3: SET QUEUE[REAR] = VAL Step 4: Exit
  • 15. Deleting an Element from a Circular Queue • To delete an element again we will check for three conditions:  If front = -1, then it means there are no elements in the queue. So an underflow condition will be reported. 0 1 2 3 4 5 6 7 8 9  If the queue is not empty and after returning the value on front, if front = rear, then it means now the queue has become empty and so front and rear are set to -1. Delete this element and set rear = front = -1 81 0 1 2 3 4 5 6 7 8 front=rear= 9  If the queue is not empty and after returning the value on front, if front = MAX -1, then front is set to 0. 72 63 9 18 27 39 81 0 1 2 3 4 rear= 5 6 7 8 front= 9
  • 16. Algorithm to Delete an Element from a Circular Queue Step 1: IF FRONT = -1, then Write “Underflow” Goto Step 4 [END OF IF] Step 2: SET VAL = QUEUE[FRONT] Step 3: IF FRONT = REAR SET FRONT = REAR = -1 ELSE IF FRONT = MAX -1 SET FRONT = 0 ELSE SET FRONT = FRONT + 1 [END OF IF] [END OF IF] Step 4: EXIT
  • 17. Deques • A deque is a list in which 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 the front (head) or back (tail). • A deque can be implemented either using a circular array or a circular doubly linked list. • In a deque, two pointers are maintained, LEFT and RIGHT which point to either end of the deque. • The elements in a deque stretch from LEFT end to the RIGHT and since it is circular, Dequeue[N-1] is followed by Dequeue[0].
  • 18. Deques • 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 the ends. Output restricted deque: In this dequeue deletions can be done only at one of the ends while insertions can be done on both the ends. 29 37 45 54 63 0 1 2 LEFT = 3 4 5 6 RIGHT = 7 8 9 42 63 27 18 RIGHT = 0 1 2 3 4 5 6 LEFT = 7 8 9
  • 19. Priority Queues • A priority queue is a queue in which each element is assigned a priority. • The priority of elements is used to determine the order in which these elements will be processed. • The general rule of processing elements of a priority queue can be given as: An element with higher priority is processed before an element with lower priority Two elements with same priority are processed on a first come first served (FCFS) basis • Priority queues are widely used in operating systems to execute the highest priority process first. • In computer’s memory priority queues can be represented using arrays or linked lists.
  • 20. Linked Representation of Priority Queues • When a priority queue is implemented using a linked list, then every node of the list contains three parts: (1) the information or data part, (ii) the priority number of the element, (iii) and address of the next element. • If we are using a sorted linked list, then element having higher priority will precede the element with lower priority. A 1 B 2 C 3 D 3 E 4 X A 1 B 2 C 3 F 4 D 5 E 6 X Priority queue after insertion of a new node
  • 21. Array Representation of Priority Queues • When arrays are used to implement a priority queue, then a separate queue for each priority number is maintained. • Each of these queues will be implemented using circular arrays or circular queues. Every individual queue will have its own FRONT and REAR pointers. • We can use a two-dimensional array for this purpose where each queue will be allocated same amount of space. • Given the front and rear values of each queue, a two dimensional matrix can be formed.
  • 22. Multiple Queues • When implementing a queue using an array, the size of the array must be known in advance. • If the queue 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, but this results in sheer wastage of memory. Thus, there lies a tradeoff between the frequency of overflows and the space allocated. • A better solution to deal with this problem is to have multiple queues or to have more than one queue in the same array. • One important point to note is that while queue A will grow from left to right, the queue B on the same time will grow from right to left. Queue A Queue B 0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1
  • 23. 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 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 OS for handling interrupts. When programming a real-time system that can be interrupted, for ex, 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
  • 24. © Oxford University Press 2014. All rights reserved. Stacks
  • 25. © Oxford University Press 2014. All rights reserved. Introduction • Stack is an important data structure which stores its elements in an ordered manner. • Take an analogy of a pile of plates where one plate is placed on top of the other. A plate can be removed only from the topmost position. Hence, you can add and remove the plate only at/from one position, that is, the topmost position. The topmost plate will be removed first Another plate will be added on top of this plate
  • 26. © Oxford University Press 2014. All rights reserved. Stacks • 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 is inserted last is the first one to be taken out. • Stacks can be implemented either using an array or a linked list.
  • 27. © Oxford University Press 2014. All rights reserved. Array Representation of Stacks • In computer’s memory stacks can be represented as a linear array. • Every stack has a variable TOP associated with it. • TOP is used to store the address of the topmost element of the stack. It is this position from where the element will be added or deleted. • There is another variable MAX which will be 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.
  • 28. © Oxford University Press 2014. All rights reserved. Push Operation • The push operation is used to insert an element in to 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 this is the case then it means the stack is full and no more insertions can further be done. • If an attempt is made to insert a value in a stack that is already full, an OVERFLOW message is printed. A B C D E 0 1 2 3 TOP = 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 TOP =5 6 7 8 9
  • 29. © Oxford University Press 2014. All rights reserved. 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 this is the case then it means the stack is empty so no more deletions can further be done. • If an attempt is made to delete a value from a stack that is already empty, an UNDERFLOW message is printed. A B C D E 0 1 2 3 TOP = 4 5 6 7 8 9 A B C D 0 1 2 TOP = 3 4 5 6 7 8 9
  • 30. © Oxford University Press 2014. All rights reserved. Peek Operation • Peek is an operation that returns the value of the topmost element of the stack without deleting it from the stack. • However, the peep operation first checks if the stack is empty or contains some elements. • If TOP = NULL, then an appropriate message is printed else the value is returned. A B C D E 0 1 2 3 TOP = 4 5 6 7 8 9 Here Peep operation will return E, as it is the value of the topmost element of the stack.
  • 31. © Oxford University Press 2014. All rights reserved. Algorithms for Push and Pop Operations Algorithm to PUSH an element in a stack Step 1: IF TOP = MAX-1, then PRINT “OVERFLOW” Goto Step 4 [END OF IF] Step 2: SET TOP = TOP + 1 Step 3: SET STACK[TOP] = VALUE Step 4: END Algorithm to POP an element from a stack Step 1: IF TOP = NULL, then PRINT “UNDERFLOW” Goto Step 4 [END OF IF] Step 2: SET VAL = STACK[TOP] Step 3: SET TOP = TOP - 1 Step 4: END
  • 32. © Oxford University Press 2014. All rights reserved. Algorithm for Peep Operation Algorithm for Peep Operation Step 1: IF TOP =NULL, then PRINT “STACK IS EMPTY” Go TO Step 3 [END OF IF] Step 2: RETURN STACK[TOP] Step 3: END
  • 33. © Oxford University Press 2014. All rights reserved. Linear Representation of Stacks • 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. • If TOP is NULL then it indicates that the stack is empty. 1 7 3 4 2 6 5 X TOP
  • 34. © Oxford University Press 2014. All rights reserved. Push Operation on a Linked Stack Algorithm to PUSH an element in a linked stack Step 1: Allocate memory for the new node and name it as New_Node Step 2: SET New_Node->DATA = VAL Step 3: IF TOP = NULL, then SET New_Node->NEXT = NULL SET TOP = New_Node ELSE SET New_node->NEXT = TOP SET TOP = New_Node [END OF IF] Step 4: END 1 7 3 4 2 6 5 X TOP 9 1 7 3 4 2 6 5 X TOP
  • 35. © Oxford University Press 2014. All rights reserved. Pop Operation on a Linked Stack Algorithm to POP an element from a stack Step 1: IF TOP = NULL, then PRINT “UNDERFLOW” Goto Step 5 [END OF IF] Step 2: SET PTR = TOP Step 3: SET TOP = TOP ->NEXT Step 4: FREE PTR Step 5: END 9 1 7 3 4 2 6 5 X TOP 1 7 3 4 2 6 5 X TOP
  • 36. © Oxford University Press 2014. All rights reserved. Multiple Stacks • When we implemented a stack using an array, we had seen that the size of the array must be known in advance. • If the stack is allocated less space, then frequent OVERFLOW conditions will be encountered. • In case, we allocate a large amount of space for the stack, it will result in sheer wastage of memory. Thus, there lies a tradeoff 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. Stack A Stack B 0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1
  • 37. © Oxford University Press 2014. All rights reserved. Applications of Stacks • 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 postfix expression • Recursion • Tower of Hanoi
  • 38. © Oxford University Press 2014. All rights reserved. Infix Notation • Infix, Postfix and Prefix notations are three different but equivalent notations of writing algebraic expressions. • While writing an arithmetic expression using infix notation, the operator is placed between the operands. For example, A+B; here, plus operator is placed between the two operands A and B. • Although it is easy to write expressions using infix notation, computers find it difficult to parse as they need a lot of information to evaluate the expression. • Information is needed about operator precedence, associativity rules, and brackets which overrides these rules. • So, computers work more efficiently with expressions written using prefix and postfix notations.
  • 39. © Oxford University Press 2014. All rights reserved. Postfix Notation • Postfix notation was given by Jan Łukasiewicz who was a Polish logician, mathematician, and philosopher. His aim was to develop a parenthesis-free prefix notation (also known as Polish notation) and a postfix notation which is better known as Reverse Polish Notation or RPN. • In postfix notation, the operator is placed after the operands. For example, if an expression is written as A+B in infix notation, the same expression can be written as AB+ in postfix notation. • The order of evaluation of a postfix expression is always from left to right.
  • 40. © Oxford University Press 2014. All rights reserved. Postfix Notation • The expression (A + B) * C is written as: AB+C* in the postfix notation. • A postfix operation does not even follow the rules of operator precedence. The operator which occurs first in the expression is operated first on the operands. • For example, given a postfix notation AB+C*. While evaluation, addition will be performed prior to multiplication.
  • 41. © Oxford University Press 2014. All rights reserved. Prefix Notation • In a prefix notation, the operator is placed before the operands. • For example, if A+B is an expression in infix notation, then the corresponding expression in prefix notation is given by +AB. • While evaluating a prefix expression, the operators are applied to the operands that are present immediately on the right of the operator. • Prefix expressions also do not follow the rules of operator precedence, associativity, and even brackets cannot alter the order of evaluation. • The expression (A + B) * C is written as: *+ABC in the prefix notation
  • 42. © Oxford University Press 2014. All rights reserved. Evaluation of an Infix Expression Algorithm to convert an Infix notation into postfix notation Step 1: Add ‘)” to the end of the infix expression Step 2: Push “(“ on to the stack Step 3: Repeat until each character in the infix notation is scanned IF a “(“ is encountered, push it on the stack IF an operand (whether a digit or an alphabet) is encountered, add it to the postfix expression. IF a “)” is encountered, then; a . Repeatedly pop from stack and add it to the postfix expression until a “(” is encountered. b. Discard the “(“. That is, remove the “(“ from stack and do not add it to the postfix expression IF an operator X is encountered, then; a Repeatedly pop from stack and add each operator (popped from the stack) to the postfix expression which has the same precedence or a higher precedence than X b. Push the operator X to the stack Step 4: Repeatedly pop from the stack and add it to the postfix expression until the stack is empty Step 5: EXIT STEP 1: Convert the infix expression into its equivalent postfix expression
  • 43. © Oxford University Press 2014. All rights reserved. Evaluation of an Infix Expression STEP 2: Evaluate the postfix expression Algorithm to evaluate a postfix expression Step 1: Add a “)” at the end of the postfix expression Step 2: Scan every character of the postfix expression and repeat steps 3 and 4 until “)”is encountered Step 3: IF an operand is encountered, push it on the stack IF an operator X is encountered, then a. pop the top two elements from the stack as A and B b. Evaluate B X A, where A was the topmost element and B was the element below A. c. Push the result of evaluation on the stack [END OF IF] Step 4: SET RESULT equal to the topmost element of the stack Step 5: EXIT
  • 44. © Oxford University Press 2014. All rights reserved. Evaluation of an Infix Expression • Let us now take an example that makes use of this algorithm. • Consider the infix expression given as “9 - (( 3 * 4) + 8) / 4”. • The infix expression "9 - (( 3 * 4) + 8) / 4" can be written as “9 3 4 * 8 + 4 / -“ using postfix notation. • Look at table which shows the procedure. Character scanned Stack 9 9 3 9, 3 4 9, 3, 4 * 9, 12 8 9, 12, 8 + 9, 20 4 9, 20, 4 / 9, 5 - 4
  • 45. © Oxford University Press 2014. All rights reserved. Convert Infix Expression into Prefix Expression Consider an infix expression: (A – B / C) * (A / K – L) • Step 1: Reverse the infix string. Note that while reversing the string you must interchange left and right parenthesis. (L – K / A) * (C / B – A) • Step 2: Obtain the corresponding postfix expression of the infix expression obtained as a result of Step 1. • The expression is: (L – K / A) * (C / B – A) • Therefore, [L – (K A /)] * [ (C B /) - A ] = [LKA/-] * [ CB/A-] = L K A / - C B / A - * • Step 3: Reverse the postfix expression to get the prefix expression • Therefore, the prefix expression is * - A / B C - / A K L
  • 46. © Oxford University Press 2014. All rights reserved. Recursion • Recursion is an implicit application of STACK ADT. • A recursive function is a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. • Every recursive solution has two major cases: the base case in which the problem is simple enough to be solved directly without making any further calls to the same function. • Recursive case, in which first the problem at hand is divided into simpler subparts. Second the function calls itself but with subparts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub-parts.
  • 47. © Oxford University Press 2014. All rights reserved. Types of Recursion • Any recursive function can be characterized based on:  whether the function calls itself directly or indirectly (direct or indirect recursion).  whether any operation is pending at each recursive call (tail- recursive or not).  the structure of the calling pattern (linear or tree-recursive). Recursion Direct Indirect Linear Tree Tail
  • 48. © Oxford University Press 2014. All rights reserved. Direct Recursion • A function is said to be directly recursive if it explicitly calls itself. • For example, consider the function given below. int Func( int n) { if(n==0) retrun n; return (Func(n-1)); }
  • 49. © Oxford University Press 2014. All rights reserved. Indirect Recursion • A function is said to be indirectly recursive if it contains a call to another function which ultimately calls it. • Look at the functions given below. These two functions are indirectly recursive as they both call each other. int Func1(int n) { if(n==0) return n; return Func2(n); } int Func2(int x) { return Func1(x-1); }
  • 50. © Oxford University Press 2014. All rights reserved. Linear Recursion • Recursive functions can also be characterized depending on the way in which the recursion grows: in a linear fashion or forming a tree structure. • In simple words, a recursive function is said to be linearly recursive when no pending operation involves another recursive call to the function. • For example, the factorial function is linearly recursive as the pending operation involves only multiplication to be performed and does not involve another call to fact() function.
  • 51. © Oxford University Press 2014. All rights reserved. Tree Recursion • A recursive function is said to be tree recursive (or non-linearly recursive) if the pending operation makes another recursive call to the function. • For example, the Fibonacci function Fib in which the pending operations recursively calls the Fib function. int Fibonacci(int num) { if(num <= 2) return 1; return ( Fibonacci (num - 1) + Fibonacci(num – 2)); }
  • 52. © Oxford University Press 2014. All rights reserved. Tail Recursion • A recursive function is said to be tail recursive if no operations are pending to be performed when the recursive function returns to its caller. • That is, when the called function returns, the returned value is immediately returned from the calling function. • Tail recursive functions are highly desirable because they are much more efficient to use as in their case, the amount of information that has to be stored on the system stack is independent of the number of recursive calls. int Fact(n) { return Fact1(n, 1); } int Fact1(int n, int res) { if (n==1) return res; return Fact1(n-1, n*res); }
  • 53. © Oxford University Press 2014. All rights reserved. Fibonacci Series • The Fibonacci series can be given as: 0 1 1 2 3 5 8 13 21 34 55…… • That is, the third term of the series is the sum of the first and second terms. Similarly, fourth term is the sum of second and third terms, so on and so forth. • A recursive solution to find the nth term of the Fibonacci series can be given as: FIB(n) = 1, if n<=2 FIB (n - 1) + FIB (n - 2), otherwise FIB(7) FIB(6) FIB(5) FIB(5) FIB(4) FIB(4) FIB(4) FIB(3) FIB(3) FIB(2) FIB(3) FIB(2) FIB(2) FIB(1) FIB(3) FIB(2) FIB(2) FIB(1) FIB(2) FIB(1) FIB(2) FIB(1) FIB(2) FIB(1) FIB(3)
  • 54. © Oxford University Press 2014. All rights reserved. Pros and Cons of Recursion Pros • Recursive solutions often tend to be shorter and simpler than non- recursive ones. • Code is clearer and easier to use. • Follows a divide and conquer technique to solve problems. • In some (limited) instances, recursion may be more efficient. Cons • For some programmers and readers, recursion is a difficult concept. • Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a deeper level will be difficult to implement. • Aborting a recursive process in midstream is slow. • Using a recursive function takes more memory and time to execute as compared to its non-recursive counterpart. • It is difficult to find bugs, particularly when using global variables.
  • 55. © Oxford University Press 2014. All rights reserved. Tower of Hanoi Tower of Hanoi is one of the main applications of a recursion. It says, "if you can solve n-1 cases, then you can easily solve the nth case" A B C A B C If there is only one ring, then simply move the ring from source to the destination B A B C A C A B C If there are two rings, then first move ring 1 to the spare pole and then move ring 2 from source to the destination. Finally move ring 1 from the source to the destination A B C
  • 56. © Oxford University Press 2014. All rights reserved. Tower of Hanoi Consider the working with three rings. A B C A B C A B C A B C A B C A B C A B C A B C