0% found this document useful (0 votes)
45 views52 pages

Unit-1 Applications of Stack - 2 - PHT - PPSX

nice book

Uploaded by

Nj
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)
45 views52 pages

Unit-1 Applications of Stack - 2 - PHT - PPSX

nice book

Uploaded by

Nj
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/ 52

Unit - 2

Stack
Linear Data Structure

Prepared By:
Ms. Purvi Tandel, Chandni Naik
Topics of Unit 2
 Array: Representation of arrays
 One dimensional array
 Two dimensional array
 Applications of array
 Stack: Concepts
 Operations on stacks
 Applications of stacks
• Polish expression
• Reverse polish expression and their compilation
 Recursion
 Tower of Hanoi
Applications of Stack
• Keeping track of function calls
• Recursion
• Evaluation of expressions
• Reversing characters
------------------------------------------------------------------------------------
• Expression Conversion (Infix to Postfix, Infix to Prefix)
• Microsoft Word (Undo / Redo)
Keeping track of function calls
• Consider an example, where we are executing function A. In the
course of its execution, function A calls another function B. Function
B in turn calls another function C, which calls function D.

• This scenario can be viewed in the form of a stack.

• In order to keep track of the returning point of each active function, a


special stack called system stack or call stack is used. Whenever a
function calls another function, the calling function is pushed onto
the top of the stack. This is because after the called function gets
executed, the control is passed back to the calling function.
Example:
When B calls C, B is pushed When C calls D, C is pushed
When A calls B, A is pushed on top of the system stack. on top of the system stack.
on top of the system stack. When the execution of C is When the execution of D is
When the execution of B is complete, the system control complete, the system control
complete, the system control will remove B from the stack Function C will remove C from the stack
will remove A from the stack and continue with its and continue with its
and continue with its Function B execution. Function B execution.
execution.
Function A Function A Function A

When D calls E, D is
pushed on top of the
Function D system stack. When the
When the execution of D When the execution of C
execution of E is
Function C complete, the Function C is complete, the system is complete, the system
system control will control will remove C for control will remove B for
Function B remove D from the stack Function B execution. Function B execution.
and continue with its
Function A execution. Function A Function A

• The whole procedure will be repeated until all the function get
executed.
• Here stack ensure a proper execution order of functions. Therefore
When the execution of B
is complete, the system stacks are frequently used in situations where the order of
Function A control will remove A for processing is very important, especially when the processing needs
execution.
to be postponed until other conditions are fulfilled.
Recursive Call
Procedure:
factorial(int n)
{
if(n==0)
return 1;
else
return n * factorial(n-1);
}
Recursive Call:
=return(5 * factorial(4))
=return(5 * return(4*factorial(3)))
=return(5 * return(4*return(3*factorial(2))))
=return(5 * return(4*return(3*return(2*factorial(1)))))
=return(5 * return(4*return(3*return(2*return(1*factorial(0))))))
=return(5 * return(4*return(3*return(2*return(1*1)))))
=return(5 * return(4*return(3*return(2*1))))
= return(5 * return(4*return(3*2)))
= return(5 * return(4*6))
= return(5 * 24)
=120
Continue..
factorial(1)
factorial(2) factorial(2)
factorial(3) factorial(3) factorial(3)
factorial(4) factorial(4) factorial(4)
factorial(4)
factorial(5) factorial(5) factorial(5)
factorial(5)
factorial(0) is factorial(1) is factorial(2) is factorial(3) is
currently executing. currently executing. currently executing. currently executing.

factorial(5)

factorial(4) is factorial(5) is
currently executing. currently executing.
Polish/Reverse Polish Expression & their Compilation
• Evaluating Infix Expression
Operand

a+b*c+d*e
1 2
Operator 3
4
 A repeated scanning from left to right is needed as operators appears inside the
operands.
 Repeated scanning is avoided if the infix expression is first converted to an
equivalent parenthesis free prefix or suffix (postfix) expression.
 Prefix Expression(Polish notation): Operator, Operand, Operand
 Postfix Expression(Reverse Polish notation): Operand, Operand, Operator
Polish/Reverse Polish Notation
• This type of notation is known Lukasiewicz Notation or Polish
Notation or Reverse Polish Notation due to Polish logician Jan
Lukasiewicz.
• In both prefix and postfix equivalents of an infix expression, the
variables are in same relative position.
• The expressions in postfix or prefix form are parenthesis free and
operators are rearranged according to rules of precedence for
operators.
Continue..
• Why do we need prefix, postfix notation??
• Infix notation is easy to read for humans, whereas pre-/postfix notation
is easier to parse for a machine.
• The big advantage in pre-/postfix notation is that there never arise any
questions like operator precedence.
• Postfix notation, is very easy to process left-to-right. An operand is
pushed onto a stack; an operator pops its operand(s) from the stack
and pushes the result. Here, Little or no parsing is necessary.
Prefix Expression(Polish notation): Operator, Operand, Operand
Continue.. Postfix Expression(Reverse Polish notation): Operand, Operand, Operator

Sr. Infix Postfix Prefix


1 a a a
2 a+b
ab+ +ab
3 a+b+c
ab+c+ ++abc
4 a + (b + c)
5 a + (b * c) abc++ +a+bc
6 a * (b + c) abc*+ +a * b c
7 a*b*c abc+* *a+bc
a b *c* ** a b c

a+b+c a+b+c (ab+)+ c (ab+) c + ab+c+


Polish/Reverse Polish Notation – Example-1
Convert Infix to Postfix Expression Convert Infix to Prefix Expression
(a+b)*b/c–d (a+b)*b/c–d
= T1 * b / c – d Where T1 = ab+ = T1 * b / c – d Where T1 = +ab
= T2 / c – d Where T2 = T1b* = T2 / c – d Where T2 = *T1b
= T3 – d Where T3 = T2c/ = T3 – d Where T3 = /T2c
= T4 Where T4 = T3d– = T4 Where T4 = – T3d
= T3 d– = – T3 d
= T2c/d– = – /T2cd
= T1b*c/d– Postfix = –/ *T1bcd Prefix
Expression Expression
= ab+b*c/d– = –/ *+abbcd
Polish/Reverse Polish Notation – Example-2
Convert Infix to Prefix Expression
Convert Infix to Postfix Expression
• (A + B) / C + D – (D * E)
• (A + B) / C + D – (D * E)
= T1 / C + D – (D * E) Where T1 = +AB
= T1 / C + D – (D * E) Where T1 = AB+
= T1 / C + D – T2 Where T2 = * DE
= T1 / C + D – T 2 Where T2 = DE*
= T3 + D – T2 Where T3 = / T1C
= T3 + D – T 2 Where T3 = T1C /
= T4 – T2 Where T4 = + T3D
= T4 – T2 Where T4 = T3D+
= T5 Where T5 = – T4 T2
= T5 Where T5 = T4 T2–
= – T4 T2
= T4 T2–
Postfix = – + T3D * DE
= T3D+ DE* – Prefix
Expression = – + / T1C D * DE Expression
= T1C / D+ DE* –
= – + / +AB C D * DE
= AB+ C / D+ DE* –
Example for Practice:
Convert following Expressions into 1) Infix to Postfix 2) Infix to Prefix
1) A – ( B / C + ( D % E * F ) / G) * H (Here * has higher priority than %)
Answer (Infix to Postfix): ABC / DEF * % G / + H * –
Answer (Infix to Prefix): – A * + / BC / % D * EFGH
2) ( a + b ^ c ^ d ) * ( e + f / d ) ) (Here Associativity of ^ is right to left)
Answer (Infix to Postfix): abcd ^^ + efd /+*
Answer (Infix to Prefix): * +a^b^cd + e/fd
Finding Rank of any Expression
• To determine whether an expression is valid, find out the rank of an
expression. If rank of an expression = 1, then expression is valid.
• Rank of an expression is determined as follows:
1) The rank of symbol Sj is “One”.
2) The rank of an operator Oj is 1 – n, where “n” is the degree of Oj.
3) The rank of an arbitrary sequence of symbols and operators is the sum of
the ranks of the individual symbols and operators.
The degree of an operator is the number of operands which that operator
Degree:
has. Example, The degree of multiplication operator is two.
The rank function which is denoted by r, is given as: (Here Symbol is a single letter
variables)
r(Sj)= 1, for 1 ≤ j ≤ 26
r(+) = r(-) = r(*) = r(/) = -1
Finding Rank of any Expression
E = ( A + B * C / D - E + F / G / ( H + I ))
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1

Rank (E) = R(A) + R(+) + R(B) + R(*) + R(C) + R (/) + R(D) + R(-) + R(E) + R (+) + R(F) + R(/) +
R(G) + R(/) + R(H) + R(+) + R(I)

Rank (E) = 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1
Rank (E) = 1
Any Expression is valid if Rank of that expression is 1
Finding Rank of any Expression: Practice example
E =ab + cd -*
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1

Rank (E) = R(a) + R(b) + R(+) + R(c) + R(d) + R (-) + R(*)


Rank (E) = 1 + 1 + (-1) + 1 + 1 + (-1) + (-1)
Rank (E) = 1

Example:
1) E= A * + / BC / % D * EFGH Answer: Invalid
2) E = abcd ^^ + efd /+* Answer: Valid
Continue..
Infix Suffix Polish Rank Valid or Invalid

a + *b ab* + 0 Invalid

a–b*c abc*– 1 Valid

ab + c abc+ 2 Invalid

(a + b) * (c – d) ab+cd–* 1 Valid

a+b/d– abd/–+ 0 Invalid


Algorithm : Infix to Postfix Conversion(UNPARENTHESIZED_SUFFIX)

• This algorithm converts INFIX into reverse polish and places the result
in the string POLISH.
• Stack is represented by a vector S, TOP denotes the top of the stack,
Algorithm PUSH and POP are used for stack manipulation.
• Function NEXTCHAR returns the next symbol in given input string.
• The integer variable RANK contains the rank of expression.
• The string variable TEMP is used for temporary storage purpose. It
contains the unstacked element.
• Variable NEXT contains the symbol being examined.
• We assume that the given input string is padded on the right with the
special symbol “#” .
Algorithm : Infix to Postfix Conversion(UNPARENTHESIZED_SUFFIX)

A general algorithm for the conversion process:


1. Initialize stack contents to the special symbol #
2. Scan the leftmost symbol in the given infix expression and denote it as the
current input symbol
3. Repeat through step 6 while the current input symbol is not #
4. Remove and output all stack symbols whose precedence values are greater
than or equal to the precedence of the current input symbol
5. Push the current input symbol onto the stack
6. Scan the leftmost symbol in the infix expression and let it be the current
input symbol
Input Content of Reverse polish Rank 6. [Push current symbol onto the
Symbo stack expression a+b*c–d/e*h
l
stack and obtain next input symbol]
1. [Initialize Stack] call PUSH (S,TOP, NEXT)
# TOP  1 NEXT  NEXTCHAR(INFIX)
0
a S[TOP] ← ‘#’ 7. [Remove remaining elements from
#a 0
+ 2. [Initialize output string stack]
#+ a 1 and rank count] Repeat while S[TOP] != ‘#’
b TEMP  POP (S, TOP)
#+b a 1 POLISH  ‘’
* RANK  0 POLISH  POLISH O TEMP
#+ * ab 2 RANK  RANK + r(TEMP)
c 3. [Get first input symbol]
#+*c ab 2 NEXT  NEXTCHAR(INFIX)
IF RANK <1
– Then write (‘INVALID’)
##+
#+*
– abc
abc*
abc*+ 321 4. [Translate the infix
d EXIT
#–d abc*+ 1 expression] 8. [Is the expression valid]
/ Repeat thru step 6
– abc*+ d IF RANK = 1
# –/ 2 while NEXT != ‘#‘
e Then write (‘VALID‘)
# –/ e abc*+ d 2 Else write (‘INVALID’)
*
# ––/* abc*+ de/
de 32 5. [Remove symbols with greater or Exit
h equal precedence from stack]
# –*h abc*+ de/ 2 Repeat while F(S[TOP]) >= F(NEXT) Symbol Precedence (F) RF (R)
#
## ––* de/h –
abc*+ de/h* 1
32 TEMP  POP (S, TOP) +, - 1 -1
POLISH  POLISH O TEMP
RANK  RANK + R(TEMP) *, / 2 -1
IF RANK <1 Variables 3 1
Then write (‘INVALID’)
EXIT # 0 -
Input Content of stack Reverse polish expression Rank
Symbol Example 2: a – b * c ^ d * e / f + g * h
5. [Remove symbols with greater
Symbol Precedence (F) RF (R) or equal precedence from stack]
# 0
+, - 1 -1 Repeat while F(S[TOP]) >= F(NEXT)
a 0 TEMP  POP (S, TOP)
#a *, / 2 -1
- # a
POLISH  POLISH O TEMP
1 ^ 3 -1 RANK  RANK + r(TEMP)
#- a 1 IF RANK <1
Variables 4 1
b Then write (‘INVALID’)
#-b a 1 # 0 - EXIT
*
ab 2 6. [Push current symbol onto the
#- stack and obtain next input
c #-* ab 2 symbol]
call PUSH (S,TOP, NEXT)
^ #-*c ab 2 NEXT  NEXTCHAR(INFIX)
1. [Initialize Stack]
#-* abc 3 TOP  1 7. [Remove remaining elements
S[TOP] ← ‘#’ from stack]
d #-*^ abc 3 Repeat while S[TOP] != ‘#’
2. [Initialize output string TEMP  POP (S, TOP)
* #-*^d abc 3 POLISH  POLISH O TEMP
and rank count] RANK  RANK + r(TEMP)
#-*^ abcd 4 POLISH  ‘’ IF RANK <1
3 RANK  0
#-* abcd^ Then write (‘INVALID’)
3. [Get first input symbol] EXIT
e #- abcd^* 2 NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid]
#-* abcd^* 2 4. [Translate the infix IF RANK = 1
expression] Then write (‘VALID‘)
#-*e abcd^* 2 Repeat thru step 6 Else write (‘INVALID’)
while NEXT != ‘#‘ Exit
Input Content of stack Reverse polish expression Rank
Symbol Continue Example 2: a – b * c ^ d * e / f + g * h
5. [Remove symbols with greater
Symbol Precedence (F) RF (R)
e #-*e abcd^* 2 or equal precedence from stack]
+, - 1 -1 Repeat while F(S[TOP]) >= F(NEXT)
/ #-* abcd^*e 3 TEMP  POP (S, TOP)
*, / 2 -1 POLISH  POLISH O TEMP
#- abcd^*e* 2 ^ 3 -1 RANK  RANK + r(TEMP)
#-/ 2 IF RANK <1
abcd^*e* Variables 4 1
f Then write (‘INVALID’)
#-/f abcd^*e* 2 # 0 - EXIT
+ 6. [Push current symbol onto the
#-/ abcd^*e*f 3
stack and obtain next input
#- abcd^*e*f/ 2 symbol]
call PUSH (S,TOP, NEXT)
# abcd^*e*f/- 1 NEXT  NEXTCHAR(INFIX)
1. [Initialize Stack]
g #+ abcd^*e*f/- 1 TOP  1 7. [Remove remaining elements
S[TOP] ← ‘#’ from stack]
* #+g abcd^*e*f/- 1 Repeat while S[TOP] != ‘#’
2. [Initialize output string TEMP  POP (S, TOP)
#+ abcd^*e*f/-g 2 POLISH  POLISH O TEMP
h #+* abcd^*e*f/-g 2
and rank count] RANK  RANK + r(TEMP)
POLISH  ‘’ IF RANK <1
# #+*h abcd^*e*f/-g 2 RANK  0 Then write (‘INVALID’)
3. [Get first input symbol] EXIT
#+* abcd^*e*f/-gh 3 NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid]
#+ abcd^*e*f/-gh* 2 4. [Translate the infix IF RANK = 1
expression] Then write (‘VALID‘)
# abcd^*e*f/-gh*+ 1 Repeat thru step 6 Else write (‘INVALID’)
while NEXT != ‘#‘ Exit
Input Content of stack Reverse polish expression Rank
Symbol Example 3: a – b * c ^ d ^ e / f + g * h
5. [Remove symbols with greater
Symbol Precedence (F) RF (R)
# 0 If operators has or equal precedence from stack]
+, - Repeat while F(S[TOP]) >= F(NEXT)
a 0 same 1 precedence -1
#a TEMP  POP (S, TOP)
*, / and associativity
2 -1 of
- POLISH  POLISH O TEMP
# a 1 ^ that operator
3 is right
-1 RANK  RANK + r(TEMP)
#- a IF RANK <1
1 Variables to left 4than we have
Note: 1
b to push the
Then write (‘INVALID’)
#-b a 1 # 0 - EXIT
* operators into the
ab 2 6. [Push current symbol onto the
#- stack rather than stack and obtain next input
c #-* ab 2 popping. symbol]
call PUSH (S,TOP, NEXT)
^ #-*c ab 2 NEXT  NEXTCHAR(INFIX)
1. [Initialize Stack]
#-* abc 3 TOP  1 7. [Remove remaining elements
S[TOP] ← ‘#’ from stack]
d #-*^ abc 3 Repeat while S[TOP] != ‘#’
2. [Initialize output string TEMP  POP (S, TOP)
^ #-*^d abc 3 POLISH  POLISH O TEMP
and rank count] RANK  RANK + r(TEMP)
#-*^ abcd 4 POLISH  ‘’ IF RANK <1
e RANK  0
#-*^^ abcd 4 Then write (‘INVALID’)
/ #-*^^e abcd 4
3. [Get first input symbol] EXIT
NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid]
#-*^^ abcde 5 4. [Translate the infix IF RANK = 1
expression] Then write (‘VALID‘)
#-*^ abcde^ 4 Repeat thru step 6 Else write (‘INVALID’)
abcde^^ while NEXT != ‘#‘ Exit
#-* 3
Input Content of stack Reverse polish expression Rank
Symbol Continue Example 3: a – b * c ^ d ^ e / f + g * h
5. [Remove symbols with greater
Symbol Precedence (F) RF (R)
/ #-* abcde^^ 3 or equal precedence from stack]
+, - 1 -1 Repeat while F(S[TOP]) >= F(NEXT)
#- abcde^^* 2 TEMP  POP (S, TOP)
*, / 2 -1 POLISH  POLISH O TEMP
#-/ abcde^^* 2 ^ 3 -1 RANK  RANK + r(TEMP)
f IF RANK <1
#-/f abcde^^* 2 Variables 4 1
+ Then write (‘INVALID’)
#-/ abcde^^*f 3 # 0 - EXIT
6. [Push current symbol onto the
#- abcde^^*f/ 2 stack and obtain next input
# abcde^^*f/- 1 symbol]
call PUSH (S,TOP, NEXT)
g #+ abcde^^*f/- 1 NEXT  NEXTCHAR(INFIX)
1. [Initialize Stack]
* #+g abcde^^*f/- 1 TOP  1 7. [Remove remaining elements
S[TOP] ← ‘#’ from stack]
#+ abcde^^*f/-g 2 Repeat while S[TOP] != ‘#’
2. [Initialize output string TEMP  POP (S, TOP)
h #+* abcde^^*f/-g 2 POLISH  POLISH O TEMP
# and rank count] RANK  RANK + r(TEMP)
#+*h abcde^^*f/-g 2 POLISH  ‘’ IF RANK <1
#+* abcde^^*f/-gh RANK  0
3 Then write (‘INVALID’)
3. [Get first input symbol] EXIT
#+ abcde^^*f/-gh* 2 NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid]
# abcde^^*f/-gh*+ 1 4. [Translate the infix IF RANK = 1
expression] Then write (‘VALID‘)
Repeat thru step 6 Else write (‘INVALID’)
while NEXT != ‘#‘ Exit
Practice Examples:

Convert Infix Expression into Postfix Expression:


(Note: Precedence of “%” is equal to precedence of “*” and “/”)

1) P * Q % R - S / T / U - V ^ W
2) P % Q % R – S * T / U * V ^ W

Answers: 1) PQ*R%ST/U/-VW^-
2) PQ%R%ST*U/VW^*-
Convert Infix to Postfix Expression(Parenthesised):
Algorithm : REVPOL
• Given an input string INFIX containing an infix expression which has
been padded on the right with ‘)’.
• This algorithm converts INFIX into reverse polish and places the result
in the string POLISH.
• All symbols have precedence value given by table.
• Stack is represented by a vector S, TOP denotes the top of the stack,
Algorithm PUSH and POP are used for stack manipulation.
• Function NEXTCHAR returns the next symbol in given input string.
• The integer variable RANK contains the rank of expression.
• The string variable TEMP is used for temporary storage purpose.
Continue..

Symbol Input Stack Rank


precedence precedence function (R)
function (F) function (G)

+, - 1 2 -1
*, / 3 4 -1
^ or ↑ 6 5 -1
Variables 7 8 1
( 9 0 -
)
All arithmetic operators 0
except exponentiation -
operator -
have an input precedence
Note: which is lower in value than their stack precedence. This preserve the left to right
processing of operators of equal precedence in expression.
Input Content of Reverse polish expression Rank
1. [Initialize Stack] (a+b^c^d)*(e+f/d)) Symbol stack
TOP  1
S[TOP] ← ‘(’ 6. [Are there matching
parentheses] ( 0
2. [Initialize output string IF G(S[TOP]) != F(NEXT) ( (( 0
and rank count] Then call PUSH (S,TOP, NEXT)
POLISH  ‘’ a ((a 0
Else POP (S,TOP)
RANK  0 + ((+
(( a 1
7. [Get next symbol]
3. [Get first input symbol] NEXT  NEXTCHAR(INFIX) b ((+b a 1
NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid] ^ ((+^
((+ ab 2
4. [Translate the infix IF TOP != 0 OR RANK != 1
c ((+^c ab 2
expression] Then write (‘INVALID‘)
Else write (‘VALID’) ^ ((+^^
((+^ abc 3
Repeat thru step 7
while NEXT != ‘ ‘ Symbol Input Stack Rank d ((+^^d abc 3
5. [Remove symbols with greater precede precedenc function ) (((+^
((
((+^^
((+ abcd
abcd^^+
abcd^^
abcd^ 34
12
precedence from stack] nce e (R) (* abcd^^+ 1
*
IF TOP < 1 function function
Then write (‘INVALID’) ( (*( abcd^^+ 1
(F) (G)
EXIT e (*( e abcd^^+ 1
Repeat while G(S[TOP]) > F(NEXT) +, - 1 2 -1
+ (*(
(*(+ abcd^^+e 2
TEMP  POP (S, TOP) *, / 3 4 -1
POLISH  POLISH O TEMP f (*(+ f abcd^^+e 2
^ or ↑ 6 5 -1
RANK  RANK + R(TEMP) Variable 7 8 1 / (*(+
(*(+/ abcd^^+ef 3
IF RANK <1 abcd^^+ef 3
s d (*(+/d
Then write (‘INVALID’)
( 9 0 - ) (*
(*(
(*(+/
(*(+ abcd^^+efd/
abcd^^+efd/+
abcd^^+efd 342
EXIT
) 0 - - ) ( abcd^^+efd/+* 1
Input Content of stack Reverse polish expression Rank
Symbol Example 2: A – ( B / C + ( D % E * F ) / G ) * H )
Symbol Input Stack Rank 4. [Translate the infix
( 0 prece preced funct expression]
A (A 0 dence ence ion
Repeat thru step 7
while NEXT != ‘ ‘
- ( A 1 functi functio (R)
5. [Remove symbols with greater
(- on (F) n (G)
A 1 precedence from stack]
( +, - 1 2 -1 IF TOP < 1
(-( A 1 Then write (‘INVALID’)
B *, / 3 4 -1 EXIT
/ (-(B A 1 ^ or ↑ 6 5 -1 Repeat while G(S[TOP]) > F(NEXT)
(-( AB TEMP  POP (S, TOP)
2 Variabl 7 8 1
POLISH  POLISH O TEMP
C (-(/ AB 2 es RANK  RANK + R(TEMP)
( 9 0 - IF RANK <1
+ (-(/C AB 2 Then write (‘INVALID’)
) 0 - - EXIT
(-(/ ABC 3
6. [Are there matching
(-( ABC/ 2 1. [Initialize Stack] parentheses]
( (-(+ ABC/ 2 TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP, NEXT)
D ABC/ 2 Else POP (S,TOP)
(-(+( 2. [Initialize output
% string 7. [Get next symbol]
(-(+(D ABC/ 2 and rank count] NEXT  NEXTCHAR(INFIX)
(-(+( ABC/D 3 POLISH  ‘’
8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
(-(+(% ABC/D 3 3. [Get first input symbol] Then write (‘INVALID‘)
NEXT  NEXTCHAR(INFIX) Else write (‘VALID’)
Input Content of stack Reverse polish expression Rank
Symbol Continue Example 2: A – ( B / C + ( D % E * F ) / G ) * H )
Symbol Input Stack Rank 4. [Translate the infix
(-(+(% ABC/D 3 expression]
prece preced funct
E (-(+(%E ABC/D 3 dence ence ion
Repeat thru step 7
while NEXT != ‘ ‘
* (-(+(% ABC/DE 4 functi functio (R)
5. [Remove symbols with greater
(-(+( on (F) n (G)
ABC/DE% 3 precedence from stack]
+, - 1 2 -1 IF TOP < 1
(-(+(* ABC/DE% 3 Then write (‘INVALID’)
F *, / 3 4 -1 EXIT
) (-(+(*F ABC/DE% 3 ^ or ↑ 6 5 -1 Repeat while G(S[TOP]) > F(NEXT)
(-(+(* ABC/DE%F TEMP  POP (S, TOP)
4 Variabl 7 8 1
POLISH  POLISH O TEMP
(-(+( ABC/DE%F* 3 es RANK  RANK + R(TEMP)
( 9 0 - IF RANK <1
/ (-(+ ABC/DE%F* 3 Then write (‘INVALID’)
) 0 - - EXIT
G (-(+/ ABC/DE%F* 3
6. [Are there matching
) (-(+/G ABC/DE%F* 3 1. [Initialize Stack] parentheses]
TOP  1 IF G(S[TOP]) != F(NEXT)
(-(+/ ABC/DE%F*G 4 S[TOP] ← ‘(’ Then call PUSH (S,TOP, NEXT)
3 Else POP (S,TOP)
(-(+ ABC/DE%F*G/ 2. [Initialize output
string 7. [Get next symbol]
(-( ABC/DE%F*G/+ 2 and rank count] NEXT  NEXTCHAR(INFIX)
* POLISH  ‘’
(- ABC/DE%F*G/+ 2 8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
(-* ABC/DE%F*G/+ 2 3. [Get first input symbol] Then write (‘INVALID‘)
NEXT  NEXTCHAR(INFIX) Else write (‘VALID’)
Input Content of stack Reverse polish expression Rank
Symbol Continue Example 2: A – ( B / C + ( D % E * F ) / G ) * H )
Symbol Input Stack Rank 4. [Translate the infix
(-* ABC/DE%F*G/+ 2 expression]
prece preced funct
H (-*H ABC/DE%F*G/+ 2 dence ence ion
Repeat thru step 7
while NEXT != ‘ ‘
) (-* ABC/DE%F*G/+H 3 functi functio (R)
5. [Remove symbols with greater
(- on (F) n (G)
ABC/DE%F*G/+H* 2 precedence from stack]
+, - 1 2 -1 IF TOP < 1
( ABC/DE%F*G/+H*- 1 Then write (‘INVALID’)
*, / 3 4 -1 EXIT
^ or ↑ 6 5 -1 Repeat while G(S[TOP]) > F(NEXT)
TEMP  POP (S, TOP)
Variabl 7 8 1
POLISH  POLISH O TEMP
es RANK  RANK + R(TEMP)
( 9 0 - IF RANK <1
Then write (‘INVALID’)
) 0 - - EXIT
6. [Are there matching
1. [Initialize Stack] parentheses]
TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
2. [Initialize output
string 7. [Get next symbol]
and rank count] NEXT  NEXTCHAR(INFIX)
POLISH  ‘’
8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
3. [Get first input symbol] Then write (‘INVALID‘)
NEXT  NEXTCHAR(INFIX) Else write (‘VALID’)
Input Content of stack Reverse polish expression Rank
Symbol Example 3: ((A – B) + D / (( E + F ) *G )) )
Symbol Input Stack Rank 4. [Translate the infix
( 0 prece preced funct expression]
( (( 0 dence ence ion
Repeat thru step 7
while NEXT != ‘ ‘
( ((( 0 functi functio (R)
5. [Remove symbols with greater
A on (F) n (G)
(((A 0 precedence from stack]
- +, - 1 2 -1 IF TOP < 1
((( A 1 Then write (‘INVALID’)
*, / 3 4 -1 EXIT
B (((- A 1 ^ or ↑ 6 5 -1 Repeat while G(S[TOP]) > F(NEXT)
(((-B A TEMP  POP (S, TOP)
) 1 Variabl 7 8 1
POLISH  POLISH O TEMP
(((- AB 2 es RANK  RANK + R(TEMP)
( 9 0 - IF RANK <1
((( AB- 1 Then write (‘INVALID’)
) 0 - - EXIT
+ (( AB- 1
6. [Are there matching
D ((+ AB- 1 1. [Initialize Stack] parentheses]
/ ((+D AB- 1 TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP, NEXT)
2 Else POP (S,TOP)
((+ AB-D 2. [Initialize output
( string 7. [Get next symbol]
((+/ AB-D 2 and rank count] NEXT  NEXTCHAR(INFIX)
( POLISH  ‘’
((+/( AB-D 2 8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
((+/(( AB-D 2 3. [Get first input symbol] Then write (‘INVALID‘)
NEXT  NEXTCHAR(INFIX) Else write (‘VALID’)
Input Content of stack Reverse polish expression Rank
Symbol Continue Example 3: ((A – B) + D / (( E + F ) *G )) )
Symbol Input Stack Rank 4. [Translate the infix
((+/(( AB-D 2 expression]
prece preced funct
E ((+/((E AB-D 2 dence ence ion
Repeat thru step 7
while NEXT != ‘ ‘
+ ((+/(( AB-DE 3 functi functio (R)
5. [Remove symbols with greater
((+/((+ on (F) n (G)
AB-DE 3 precedence from stack]
F +, - 1 2 -1 IF TOP < 1
((+/((+F AB-DE 3 Then write (‘INVALID’)
) *, / 3 4 -1 EXIT
((+/((+ AB-DEF 4 ^ or ↑ 6 5 -1 Repeat while G(S[TOP]) > F(NEXT)
((+/(( AB-DEF+ TEMP  POP (S, TOP)
3 Variabl 7 8 1
POLISH  POLISH O TEMP
* ((+/( AB-DEF+ 3 es RANK  RANK + R(TEMP)
( 9 0 - IF RANK <1
G ((+/(* AB-DEF+ 3 Then write (‘INVALID’)
) 0 - - EXIT
) ((+/(*G AB-DEF+ 3
6. [Are there matching
((+/(* AB-DEF+G 4 1. [Initialize Stack] parentheses]
TOP  1 IF G(S[TOP]) != F(NEXT)
((+/( AB-DEF+G* 3 S[TOP] ← ‘(’ Then call PUSH (S,TOP, NEXT)
) AB-DEF+G* 3 Else POP (S,TOP)
((+/ 2. [Initialize output
string 7. [Get next symbol]
((+ AB-DEF+G*/ 2 and rank count] NEXT  NEXTCHAR(INFIX)
(( AB-DEF+G*/+ 1 POLISH  ‘’
) 8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
( AB-DEF+G*/+ 1 3. [Get first input symbol] Then write (‘INVALID‘)
Empty AB-DEF+G*/+ 1 NEXT  NEXTCHAR(INFIX) Else write (‘VALID’)
Practice Examples:

Convert Infix Expression into Postfix Expression:

1) ( A – B * ( C + D ) / E * F ) + G
2) ( A / B / ( C + D ) * E ^ F ^ G – H * ( I / J ) )

Answers: 1) ABCD+*E/F*-G+
2) AB/CD+/EFG^^*HIJ/*-
General Infix-to-Postfix Conversion
Create an empty stack called stack for keeping operators. Create an empty list for
output.
Read the character list from left to right and perform following steps
If the character is an operand (Variable), append it to the end of the output list
If the character is a left parenthesis ‘(’, push it on the stack
If the character is a right parenthesis ‘)’, pop the stack until the corresponding left parenthesis ‘)’ is
removed. Append each operator to the end of the output list.

If the token is an operator, *, /, +, or -, push it on the stack. However, first remove any operators
already on the stack that have higher or equal precedence and append them to the output list.
(Condition : if (input operator >= Stack TOP operator) then push
else while (input operator < Stack TOP operator) then pop)

(a+b^c^d)*(e+f/d)
Infix to Prefix Conversion
• To convert from infix to prefix expression, arrange expression in reverse
order.
• Apply generalized algorithm we used to convert infix to postfix.
• Once you get output string, reverse that output string.
• Reverse output string will be the answer of Infix to Prefix expression
conversion.
Ex: a + b / c
 Step 1 – c / b + a (Reverse String)
 Step 2 – Postfix result – c b / a +
 Step 3 – + a / b c (Reserve String given in Step 2 – final answer)
Example:

Convert Infix expression ( A - B / C ) * ( A / K - L ) into Prefix expression.


• Step 1: Reverse the infix string.
Reverse String: (L – K / A)*(C / B – A)
Final string to trace: (L – K / A)*(C / B – A))
• Step 2: Obtain the corresponding postfix expression.
• Step 3: Reverse the postfix expression to get the prefix expression.
Input Content of Reverse polish expression Rank
1. [Initialize Stack] (L – K / A)*(C / B – A)) Symbol stack
TOP  1
S[TOP] ← ‘(’ 6. [Are there matching 0
parentheses] (
2. [Initialize output string 0
IF G(S[TOP]) != F(NEXT) ( ((
and rank count]
POLISH  ‘’ Then call PUSH (S,TOP, NEXT) L ((L 0
RANK  0 Else POP (S,TOP)
– ((–
(( L 1
3. [Get first input symbol] 7. [Get next symbol]
NEXT  NEXTCHAR(INFIX) K ((–K L 1
NEXT  NEXTCHAR(INFIX)
4. [Translate the infix
8. [Is the expression valid] / ((– / LK 2
expression] IF TOP != 0 OR RANK != 1 LK
A ((–/A 2
Repeat thru step 7 Then write (‘INVALID‘)
Else write (‘VALID’) ) ((–
(((
((–/ LKA/–
LKA/
LKA 321
while NEXT != ‘ ‘
5. [Remove symbols with Symbol Input Stack Rank * (* LKA/ – 1
greater precede precedenc function ( (*( LKA/ – 1
precedence from stack]
nce e (R) C (* ( C LKA/ – 1
IF TOP < 1
Then write (‘INVALID’) function function / LKA/ – C 2
(*( /
EXIT (F) (G) (*( /B LKA/ – C 2
B
Repeat while G(S[TOP]) > +, - 1 2 -1
– (*((–/
(* LKA/ – CB / 32
F(NEXT) *, / 3 4 -1
TEMP  POP (S, TOP) A (*(–A LKA / – CB / 2
^ or ↑ 6 5 -1
POLISH  POLISH O TEMP
) (*( –
(* LKA / – CB / A – 32
RANK  RANK + R(TEMP) Variable 7 8 1
IF RANK <1 s ) ( LKA / – CB / A – * 1
Then write (‘INVALID’) ( 9 0 -
EXIT Prefix Expression: * – A / BC – / AKL
) 0 - - )
Practice Example: Convert Infix Expression to Prefix Expression

1) (A + B) * C / D + E ↑ F / G
2) A – B / ( C * D ↑ E)
Evaluation of postfix expression
• Each operator in postfix string refers to the previous two operands in the
string.
• Each time we read an operand, we PUSH it onto Stack.
• When we reach an operator, its operands will be top two elements on the
stack.
• We can then POP these two elements, perform the indicated operation on
them and PUSH the result on the stack so that it will available for use as an
operand of the next operator.
Evaluation of postfix expression
Evaluate Expression: 5 6 2 - +
Empty Stack
Read - , it is operator? POP
Read 5, it is operand? PUSH
two symbols and perform
Read 6, it is operand? PUSH operation and PUSH result
Read 2, it is operand? PUSH
2
6 4
5 Operand 1 - Operand 2 5

Read next symbol, Read + , it is operator? POP


if is it is end of two symbols and perform
string, POP answer operation and PUSH result
from Stack

Answer 9 Operand 1 + Operand 2


Algorithm: EVALUAE_POSTFIX
• Given an input string POSTFIX representing postfix expression.
• This algorithm evaluates postfix expression and put the result into
variable VALUE.
• Stack is represented by a vector S, TOP denotes the top of the stack,
Algorithm PUSH and POP are used for stack manipulation.
• Function NEXTCHAR returns the next symbol in given input string.
• OPERAND1, OPERAND2 and TEMP are used for temporary variables
• PERFORM_OPERATION is a function which performs required operation
on OPERAND1 & OPERAND2.
Algorithm & Example: EVALUAE_POSTFIX
Evaluate Expression: 5 2 3 + * 12 6 / -
1. [Initialize Stack]
TOP  0
VALUE  0 3 6
2. [Evaluate the postfix expression]
Repeat until last character 2 5 12
TEMP  NEXTCHAR (POSTFIX)
5 5 25 25
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND2  POP (S, TOP)
OPERAND1  POP (S, TOP)
VALUE 
PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE) 2

25 23
3. [Return answer from stack]
Return (POP (S, TOP))
Practice Example: Evaluation of postfix expression

Evaluate Expression: 7 5 2 + * 4 1 1 + / -

Evaluate Expression: 12, 7, 3, -, /, 2, 1, 5, +, *, +


Tower of Hanoi Problem
• Tower of Hanoi, is a mathematical puzzle which consists of three towers 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.
Tower of Hanoi Problem
• Rules:
• The mission is to move all the disks to some another tower without
violating the sequence of arrangement. A few rules to be followed for
Tower of Hanoi 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.
• Tower of Hanoi puzzle with “n” disks can be solved in minimum 2n−1 steps.
• In above, shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
1-Disk Problem

A B C
(Source) (Middle) (Destination)

• Move a disc from A to C


2-Disk Problem

A B C
(Source) (Middle) (Destination)

• Move a disc from A to B using C


• Move a disc from A to C
• Move a disc from B to C using A
Tower of Hanoi Problem Hanoi(3, 1,2,3)

ALGORITHM:
START Hanoi(2, 1,3,2)
Procedure Hanoi(n, A, B, C)
1-3 Hanoi(2, 2,1,3)
IF disk == 1, THEN
move disk from A to C
ELSE
Hanoi(1, 1,2,3) 1-2
Hanoi(n - 1, A, C, B) // Step 1 Hanoi(1, 3,1,2) Hanoi(1, 2,3,1) 2-3 Hanoi(1, 1,2,3)
move disk from A to C// Step 2
Hanoi(n - 1, B, A, C) // Step 3
END IF 1-3 3-2 2-1 1-3
END Procedure
STOP

Tracing for 3- Discs


(1-3) (1-2) (3-2) (1-3) (2-1) (2-3) (1-3)
a) 1-3 b) 1-2

A B C A B C A B C
(Source) (Middle) (Destination) (Source) (Middle) (Destination) (Source) (Middle) (Destination)

c) 3-2
d) 1-3 e) 2-1

A B C A B C A B C
(Source) (Middle) (Destination) (Source) (Middle) (Destination) (Source) (Middle) (Destination)

f) 2-3 f) 1-3

A B C A B C
(Source) (Middle) (Destination) (Source) (Middle) (Destination)
Thank you

You might also like