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

Unit-1 Applications of Stack_2_PHT

Unit 2 covers stacks as a linear data structure, detailing array representation, operations on stacks, and their applications such as function call tracking and expression evaluation. It explains the conversion of infix expressions to postfix and prefix notations, emphasizing the advantages of using these notations for machine parsing. Additionally, the document includes algorithms for infix to postfix conversion and methods to determine the validity of expressions based on their rank.

Uploaded by

dhruvp454545
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit-1 Applications of Stack_2_PHT

Unit 2 covers stacks as a linear data structure, detailing array representation, operations on stacks, and their applications such as function call tracking and expression evaluation. It explains the conversion of infix expressions to postfix and prefix notations, emphasizing the advantages of using these notations for machine parsing. Additionally, the document includes algorithms for infix to postfix conversion and methods to determine the validity of expressions based on their rank.

Uploaded by

dhruvp454545
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, 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 When C calls D, C is
When A calls B, A is pushed on top of the pushed on top of the
pushed on top of the system stack. When system stack. When
system stack. When the execution of C is the execution of D is
the execution of B is complete, the system Function C complete, the system
complete, the system control will remove B control will remove C
control will remove A Function B from the stack and Function B from the stack and
from the stack and
Function A continue with its continue with its
continue with its Function A execution. Function A execution.
execution.
When D calls E, D is
pushed on top of the
Function D system stack. When
When the execution When the execution
the execution of E is
of D is complete, of C is complete, the
Function C complete, the Function C the system control system control will
system control will
Function B remove D from the Function B will remove C for Function B remove B for
stack and continue execution. execution.
Function A with its 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 stacks are frequently used in situations where the order of
Function A system 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.
Continue..
Prefix Expression(Polish notation): Operator, Operand, Operand
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
Postfix Prefix
= T1b*c/d– Expression = –/ *T1bcd 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 – T 2 Where T2 = * DE
= T1 / C + D – T 2 Where T2 = DE*
= T3 + D – T 2 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–
= – T 4 T2
= T4 T2–
Postfix = – + T3D * DE Prefix
= T3D+ DE* – Expression Expression
= – + / T1C D * DE
= 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
stack and obtain next input
l 1. [Initialize Stack] symbol]
# TOP  1
0 call PUSH (S,TOP, NEXT)
S[TOP] ← ‘#’ NEXT  NEXTCHAR(INFIX)
a #a 0 7. [Remove remaining elements
+ 2. [Initialize output string from stack]
#+ a 1 Repeat while S[TOP] != ‘#’
b #+b a 1 and rank count] TEMP  POP (S, TOP)
* POLISH  ‘’ POLISH  POLISH O TEMP
#+ * ab 2 RANK  RANK + r(TEMP)
c RANK first
3. [Get  0 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 IF RANK = 1

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

All arithmetic operators 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,
POLISH  ‘’ a ((a 0
NEXT)
RANK  0 Else next
POP (S,TOP) + ((+
(( a 1
7. [Get 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 precede precedenc function ) (((+^
((
((+^^
((+ abcd
abcd^^+
abcd^^
abcd^ 34
12
greater nce e (R) (* abcd^^+ 1
*
precedence from stack] function function
IF TOP < 1 ( (*( abcd^^+ 1
(F) (G)
Then write (‘INVALID’) e (*( e abcd^^+ 1
EXIT +, - 1 2 -1
+ (*(
(*(+ abcd^^+e 2
Repeat while G(S[TOP]) > *, / 3 4 -1
F(NEXT) f (*(+ f abcd^^+e 2
^ or ↑ 6 5 -1
TEMP  POP (S, TOP) Variable 7 8 1 / (*(+
(*(+/ abcd^^+ef 3
POLISH  POLISH O TEMP abcd^^+ef 3
s d (*(+/d
RANK  RANK + R(TEMP)
( 9 0 - ) (*
(*(+
(*(
(*(+/ abcd^^+efd/
abcd^^+efd/+
abcd^^+efd 342
IF RANK <1
Then write (‘INVALID’) ) 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
(- A 1 on (F) n (G) greater
( +, - 1 2 -1 precedence from stack]
(-( A 1 IF TOP < 1
B *, / 3 4 -1 Then write (‘INVALID’)
/ (-(B A 1 ^ or ↑ 6 5 -1 EXIT
(-( AB 2 Variabl 7 8 1
Repeat while G(S[TOP]) >
F(NEXT)
C (-(/ AB 2 es TEMP  POP (S, TOP)
( 9 0 - POLISH  POLISH O TEMP
+ (-(/C AB 2 RANK  RANK + R(TEMP)
) 0 - - IF RANK <1
(-(/ ABC 3 Then there
write matching
(‘INVALID’)
6. [Are
ABC/ 2 EXIT
(-( 1. [Initialize Stack] parentheses]
( (-(+ ABC/ 2
TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP,
D ABC/ 2 NEXT)
(-(+( 2. [Initialize output
% string
Else POP (S,TOP)
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 Then write (‘INVALID‘)
symbol] 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
(-(+( ABC/DE% 3 on (F) n (G) greater
+, - 1 2 -1 precedence from stack]
(-(+(* ABC/DE% 3 IF TOP < 1
F *, / 3 4 -1 Then write (‘INVALID’)
) (-(+(*F ABC/DE% 3 ^ or ↑ 6 5 -1 EXIT
(-(+(* ABC/DE%F 4 Variabl 7 8 1
Repeat while G(S[TOP]) >
F(NEXT)
(-(+( ABC/DE%F* 3 es TEMP  POP (S, TOP)
( 9 0 - POLISH  POLISH O TEMP
/ (-(+ ABC/DE%F* 3 RANK  RANK + R(TEMP)
) 0 - - IF RANK <1
G (-(+/ ABC/DE%F* 3 Then there
write matching
(‘INVALID’)
6. [Are
) (-(+/G ABC/DE%F* 3 1. [Initialize Stack]
EXIT
parentheses]
TOP  1 IF G(S[TOP]) != F(NEXT)
(-(+/ ABC/DE%F*G 4 S[TOP] ← ‘(’ Then call PUSH (S,TOP,
(-(+ ABC/DE%F*G/ 3 2. [Initialize output
NEXT)
Else POP (S,TOP)
string 7. [Get next symbol]
(-( ABC/DE%F*G/+ 2
* and rank count] NEXT  NEXTCHAR(INFIX)
(- ABC/DE%F*G/+ 2 POLISH  ‘’
8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
(-* ABC/DE%F*G/+ 2 3. [Get first input Then write (‘INVALID‘)
symbol] 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
(- ABC/DE%F*G/+H* 2 on (F) n (G) greater
+, - 1 2 -1 precedence from stack]
( ABC/DE%F*G/+H*- 1 IF TOP < 1
*, / 3 4 -1 Then write (‘INVALID’)
^ or ↑ 6 5 -1 EXIT
Repeat while G(S[TOP]) >
Variabl 7 8 1
F(NEXT)
es TEMP  POP (S, TOP)
( 9 0 - POLISH  POLISH O TEMP
RANK  RANK + R(TEMP)
) 0 - - IF RANK <1
Then there
6. [Are write matching
(‘INVALID’)
EXIT
parentheses]
1. [Initialize Stack]
TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP,
NEXT)
2. [Initialize output
Else POP (S,TOP)
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 Then write (‘INVALID‘)
symbol] 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
A
(((A 0 on (F) n (G) greater
- +, - 1 2 -1 precedence from stack]
((( A 1 IF TOP < 1
*, / 3 4 -1 Then write (‘INVALID’)
B (((- A 1 ^ or ↑ 6 5 -1 EXIT
) (((-B A 1 Variabl 7 8 1
Repeat while G(S[TOP]) >
F(NEXT)
(((- AB 2 es TEMP  POP (S, TOP)
( 9 0 - POLISH  POLISH O TEMP
((( AB- 1 RANK  RANK + R(TEMP)
) 0 - - IF RANK <1
+ (( AB- 1 Then there
write matching
(‘INVALID’)
6. [Are
D ((+ AB- 1 1. [Initialize Stack]
EXIT
parentheses]
/ ((+D AB- 1 TOP  1 IF G(S[TOP]) != F(NEXT)
S[TOP] ← ‘(’ Then call PUSH (S,TOP,
((+ AB-D 2 2. [Initialize output
NEXT)
( string
Else POP (S,TOP)
7. [Get next symbol]
((+/ AB-D 2
( and rank count] NEXT  NEXTCHAR(INFIX)
((+/( AB-D 2 POLISH  ‘’
8. [Is the expression valid]
RANK  0
IF TOP != 0 OR RANK != 1
((+/(( AB-D 2 3. [Get first input Then write (‘INVALID‘)
symbol] 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
((+/((+ AB-DE 3 on (F) n (G) greater
F +, - 1 2 -1 precedence from stack]
((+/((+F AB-DE 3 IF TOP < 1
) *, / 3 4 -1 Then write (‘INVALID’)
((+/((+ AB-DEF 4 ^ or ↑ 6 5 -1 EXIT
((+/(( AB-DEF+ 3 Variabl 7 8 1
Repeat while G(S[TOP]) >
F(NEXT)
* ((+/( AB-DEF+ 3 es TEMP  POP (S, TOP)
( 9 0 - POLISH  POLISH O TEMP
G ((+/(* AB-DEF+ 3 RANK  RANK + R(TEMP)
) 0 - - IF RANK <1
) ((+/(*G AB-DEF+ 3 Then there
write matching
(‘INVALID’)
6. [Are
AB-DEF+G 4 EXIT
((+/(* 1. [Initialize Stack] parentheses]
TOP  1 IF G(S[TOP]) != F(NEXT)
((+/( AB-DEF+G* 3 S[TOP] ← ‘(’ Then call PUSH (S,TOP,
) AB-DEF+G* 3 NEXT)
((+/ 2. [Initialize output
Else POP (S,TOP)
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 Then write (‘INVALID‘)
Empty AB-DEF+G*/+ 1 symbol] 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 ( 0
IF G(S[TOP]) != F(NEXT) ((
string
and rank count] Then call PUSH (S,TOP, L ((L 0
POLISH  ‘’ NEXT)
– ((–
(( L 1
RANKfirst
 0 input Elsenext
7. [Get POP symbol]
(S,TOP)
3. [Get
NEXT  NEXTCHAR(INFIX) K ((–K L 1
symbol]
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
Variable 7 8 1 ) (*( –
(* LKA / – CB / A – 32
RANK  RANK + R(TEMP)
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) 2
PUSH (S, POP, VALUE)
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 Hanoi(3, 1,2,3)

Problem
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