SlideShare a Scribd company logo
Unit-3
Linear Data Structure (Stack)
Stack
 A linear list which allows insertion and deletion of an element at one end only is
called stack.
 The insertion operation is called as PUSH and deletion operation as POP.
 The most accessible elements in stack is known as top.
 The elements can only be removed in the opposite orders from that in which
they were added to the stack.
 Such a linear list is referred to as a LIFO (Last In First Out) list.
… …
TOP
Insertio
n
Deletion
A
B
C
Stack Cont…
 A pointer TOP keeps track of the top element in the stack.
 Initially, when the stack is empty, TOP has a value of “-1”.
 Each time a new element is inserted in the stack, the pointer is incremented
by “one” before, the element is placed on the stack.
 The pointer is decremented by “one” each time a deletion is made from the
stack.
Applications of Stack
 Recursion (
https://cdn-media-1.freecodecamp.org/images/1*fsYHEgadIdn0fJt-cBXDHQ.gif)
 Keeping track of function calls
 Evaluation of expressions
 Reversing characters
 Servicing hardware interrupts
 Solving combinatorial problems using backtracking
 Expression Conversion (Infix to Postfix, Infix to Prefix)
 Game Playing (Chess)
 Microsoft Word (Undo / Redo)
 Compiler – Parsing syntax & expression
 Finding paths
Procedure : PUSH (S, TOP, X)
 This procedure inserts an element X to the top of a stack.
 Stack is represented by a vector S containing N elements.
 A pointer TOP represents the top element in the stack.
1. [Check for stack overflow]
If TOP ≥ N-1
Then write (‘STACK
OVERFLOW’)
Return
2. [Increment TOP]
TOP ← TOP + 1
3. [Insert Element]
S[TOP] ← X
4. [Finished]
Return
S
Stack is empty, TOP = -1,
N=3
PUSH(S, TOP,
10)
TOP =
0
10
PUSH(S, TOP,
8)
TOP =
1
8
PUSH(S, TOP, -
5)
TOP = 2 -5
PUSH(S, TOP, 6)
Overflow
Function : POP (S, TOP)
 This function removes & returns the top element from a stack.
 Stack is represented by a vector S containing N elements.
 A pointer TOP represents the top element in the stack.
1. [Check for stack underflow]
If TOP = -1
Then write (‘STACK
UNDERFLOW’)
Return (0)
2. [Decrement TOP]
TOP ← TOP - 1
3. [Return former top element of
stack]
Return(S[TOP + 1])
S
10
8
-5
POP(S, TOP) TOP = 2
TOP =
1
POP(S, TOP)
TOP =
0
POP(S, TOP)
TOP = -
1
POP(S, TOP)
Underflow
Function : PEEP (S, TOP, I)
 This function returns the value of the Ith
element from the TOP of the stack.
The element is not deleted by this function.
 Stack is represented by a vector S containing N elements.
1. [Check for stack underflow]
If TOP-I+1 ≤ -1
Then write (‘STACK
UNDERFLOW’)
Return (0)
2. [Return Ith
element from top
of the stack]
Return(S[TOP–I+1])
S
10
8
-5
TOP = 2
PEEP (S, TOP,
2) 8
PEEP (S, TOP,
3)
10
PEEP (S, TOP,
4)
Underflo
w
PROCEDURE : CHANGE (S, TOP, X, I)
 This procedure changes the value of the Ith
element from the top of the stack to
X.
 Stack is represented by a vector S containing N elements.
1. [Check for stack underflow]
If TOP-I+1 ≤ -1
Then write (‘STACK
UNDERFLOW’)
Return
2. [Change Ith
element from top
of the stack]
S[TOP–I+1] ← X
3. [Finished]
Return
S
10
8
-5
TOP = 2
CHANGE (S, TOP, 50,
2) 50
CHANGE (S, TOP, 9, 3)
9
CHANGE (S, TOP, 25,
8)
Underflow
Polish Expression & their Compilation
 Evaluating Infix Expression
a + b * c + d * e
1 2
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: Operator, Operand, Operand
 Postfix Expression: Operand, Operand, Operator
(a + b) * (c + d) * e
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.
Polish Notation
Sr. Infix Postfix Prefix
1 a
2 a + b
3 a + b + c
4 a + (b + c)
5 a + (b * c)
6 a * (b + c)
7 a * b * c
a a
a b + + a b
a + b + c a + b + c (ab+)+ c (ab+) c + a b + c +
a b + c + + + a b c
a b c + + + a + b c
a b c * + +a * b c
a b c + * * a + b c
a b *c* ** a b c
Finding Rank of any Expression
E = ( A + B * C / D - E + F / G / ( H + I ))
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)
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1
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
Infix and postfix
 Conventional notation is called infix notation.
 Parentheses are required to specify the order of the
operations. For example: a * b + c
 Postfix notation (also known as reverse Polish notation)
eliminates the need for parentheses.
 There are no precedence rules to learn, and parentheses are
never needed.
Infix to postfix Conversion
Let us use a stack
1. When an operand is read, output it
2. When an operator is read
• Pop until the top of the stack has an element of lower
precedence
• Then push it
3. When ) is found, pop until we find the matching (
4. ( has the lowest precedence when in the stack but has the
highest precedence when in the input
5. When we reach the end of input, pop until the stack is empty
Infix to postfix Conversion
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variabl
es
7 8 1
( 9 0 -
infixVect
postfixVect
( a + b - c ) * d – ( e + f )
Infix to postfix conversion
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
a + b - c ) * d – ( e + f )
(
stackVect
Infix to postfix conversion
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
+ b - c ) * d – ( e + f )
(
a
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
b - c ) * d – ( e + f )
(
a
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
- c ) * d – ( e + f )
(
a b
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
c ) * d – ( e + f )
(
a b +
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
) * d – ( e + f )
(
a b + c
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
* d – ( e + f )
a b + c -
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
d – ( e + f )
a b + c -
*
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
– ( e + f )
a b + c - d
*
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
( e + f )
a b + c – d *
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
e + f )
a b + c – d *
-
(
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
+ f )
a b + c – d * e
-
(
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
f )
a b + c – d * e
-
(
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
)
a b + c – d * e f
-
(
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
a b + c – d * e f +
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
infixVect
postfixVect
a b + c – d * e f + -
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
3 + 4 * 5 / 6
Exercise
(300 + 23) * (43 - 21) / (84 + 7)
(4 + 8) * (6 - 5) / ((3 – 2) * (2 + 2))
((a + b) – c * d + (t * 4))
(((ab + t – 6) * 5) – (5 + x) / z)
Symbol
Stack
precedenc
e
function
(G)
+, - 2
*, / 4
^ 5
Variabl
es
8
( 0
) -
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 the 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.
Infix to postfix Conversion
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variabl
es
7 8 1
( 9 0 -
Input
Symbol
Content
of stack
Reverse polish
expression
Rank
(( a + b ^ c ^ d ))
NEXT
1. [Initialize Stack]
TOP  0
S[TOP] ← ‘(’
(
2. [Initialize output string and rank
count]
POLISH  ‘’
RANK  0
0
3. [Get first input symbol]
NEXT  NEXTCHAR(INFIX)
(
Input
Symbol
Content of
stack
Reverse
polish
expression
Rank
( a + b ^ c ^ d )
NEXT
( 0
(
4. [Translate the infix expression]
Repeat thru step 7
while NEXT!= ‘)‘
5. [Remove symbols with greater precedence from
stack]
IF TOP < 0
Then write (‘INVALID’)
EXIT
Repeat while G(S[TOP]) > F(NEXT)
TEMP  POP (S, TOP)
POLISH  POLISH O TEMP
RANK  RANK + R(TEMP)
IF RANK < 0
Then write (‘INVALID’)
EXIT
6. [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
7. [Get next symbol]
NEXT  NEXTCHAR(INFIX)
(( 0
a ((a 0
+ (( a 1
((+
b ((+b a 1
^ ((+ ab 2
((+^
c ((+^c ab 2
^ ((+^ abc 3
((+^^
d ((+^^d abc 3
) (( abcd^^+ 1
(
1. [Initialize Stack]
TOP  0
S[TOP] ← ‘(’
2. [Initialize output string and rank
count]
POLISH  ‘’
RANK  0
3. [Get first input symbol]
NEXT  NEXTCHAR(INFIX)
4. [Translate the infix expression]
Repeat thru step 7
while NEXT != ‘)‘
5. [Remove symbols with greater
precedence from stack]
IF TOP < 0
Then write (‘INVALID’)
EXIT
Repeat while G(S[TOP]) > F(NEXT)
TEMP  POP (S, TOP)
POLISH  POLISH O TEMP
RANK  RANK + R(TEMP)
IF RANK < 0
Then write (‘INVALID’)
EXIT
6. [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
7. [Get next symbol]
NEXT  NEXTCHAR(INFIX)
8. [Is the expression valid]
IF TOP != -1 OR RANK != 0
Then write (‘INVALID‘)
Else write (‘VALID’)
Symbol IPF (F) SPF (G) RF (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -
2
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
1
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.
3
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.
4
Infix: ( a + b ^ c ^ d ) * ( e + f / d )
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function
(R)
+, - 1 2 -1
*, / 3 4 -1
^, $ 6 5 -1
Variable 7 8 1
Postfix: a b c ^ d ^ + e f d / + *
Perform following operations
 Convert the following infix expression to postfix. Show the stack contents.
 A$B-C*D+E$F/G
 A+B–C*D*E$F$G
 a+b*c-d/e*h
 ((a+b^c^d)*(e+f/d))
 Convert the following infix expression to prefix.
 A + B – C * D * E ^ F ^ G
 Step 1: Reverse infix input string
 Step 2: Convert reverse infix of step 1 into postfix
 Step 3: Reverse postfix expression of step 2
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function
(R)
+, - 1 2 -1
*, / 3 4 -1
^, $ 6 5 -1
Variable
s
7 8 1
( 9 0 -
) 0 - -
AB$CD*-EF$G/+
AB+CD*EF$G$*-
abc*+de/h*-
abc^d^+efd/+*
G ^ F ^ E * D * C – B + A
G F ^ E ^ D * C – B * A+
+A * B – C * D ^ E ^ F G
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 be available for use as an
operand for the next operator.
Evaluation of postfix expression
Evaluate Expression: 5 6 2 - +
Empty
Stack Read 5, is it operand?
PUSH
5
Read 6, is it operand?
PUSH
6
Read 2, is it operand?
PUSH
2
Read – , is it operator?
POP two symbols and
perform operation
and PUSH result
Operan
d 1
Operan
d 2
– 5
4
Read + , is it operator?
POP two symbols and
perform operation and
PUSH result
Operan
d 1
Operan
d 2
+
Read next symbol,
if it is end of
string, POP
answer from
Stack
Answe
r
9
Algorithm: EVALUATE_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: EVALUATE_POSTFIX
1. [Initialize Stack]
TOP  -1
VALUE  0
2. [Evaluate the postfix expression]
Repeat until last character
TEMP  NEXTCHAR (POSTFIX)
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)
3. [Return answer from stack]
Return (POP (S, TOP))
Evaluation of postfix expression
Evaluate Expression: 5 4 6 + * 4 9 3 / + *
Evaluate Expression: 7 5 2 + * 4 1 1 + / -
Evaluate Expression: 12, 7, 3, -, /, 2, 1, 5, +, *, +
350
47
15
Algorithm: EVALUATE_PREFIX
 Given an input string PREFIX representing prefix expression.
 This algorithm evaluates prefix 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: EVALUATE_PREFIX
1. [Initialize Stack]
TOP  -1
VALUE  0
2. [Evaluate the prefix expression]
Repeat from last character up to first
TEMP  NEXTCHAR (PREFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND1  POP (S, TOP)
OPERAND2  POP (S, TOP)
VALUE  PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
Recursion
A procedure that contains a procedure call to itself or a procedure call to
second procedure which eventually causes the first procedure to be called
is known as recursive procedure.
Two important conditions for any recursive procedure
Each time a procedure calls itself it must be nearer in some sense to a solution.
1
There must be a decision criterion for stopping the process or computation.
2
Two types of recursion
This is recursive defined function.
E.g. Factorial function
Primitive Recursion
This is recursive use of procedure.
E.g. Find GCD of given two numbers
Non-Primitive
Recursion
The Towers of Hanoi
• In the great temple of Brahma in Benares, on a brass plate under
the dome that marks the center of the world, there are 64 disks of
pure gold that the priests carry one at a time between these
diamond needles according to Brahma's immutable law:
• No disk may be placed on a smaller disk. In the begging of the
world all 64 disks formed the Tower of Brahma on one needle.
Now, however, the process of transfer of the tower from one needle
to another is in mid course.
• When the last disk is finally in place, once again forming the Tower
of Brahma but on a different needle, then will come the end of the
world and all will turn to dust.
Is the End of the World Approaching?
• 64 gold discs
• Given 1 move a second
• Problem complexity 2n
584,942,417,355 years
five hundred eighty-four billion nine hundred forty-two million four
hundred seventeen thousand three hundred fifty-five years
The Towers of Hanoi --- A Stack-based Application
• GIVEN: three poles
• a set of discs on the first pole, discs of different sizes, the smallest discs
at the top
• GOAL: move all the discs from the left pole to the right one.
• CONDITIONS: only one disc may be moved at a time.
• A disc can be placed either on an empty pole or on top of a larger disc.
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi
A
B C
Towers of Hanoi – Implementation
using ‘C’
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
count++;
TOH(n-1,x,z,y);
printf("n%c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n=3;
TOH(n,'A','B','C');
printf(“nTotal steps are %d",count);
}
#include<stdio.h>
int count=0;
Thank
You
Algorithm: RECOGNIZE
Write an algorithm which will check that the given string belongs to following
grammar or not.
L= {wcwR
| w Є {a,b}*
} (Where wR
is the reverse of w)
• Given an input string named STRING on the alphabet {a, b, c} which contains a blank in
its rightmost character position.
• Function NEXTCHAR returns the next symbol in STRING.
• This algorithm determines whether the contents of STRING belong to the above
language.
• The vector S represents the stack and TOP is a pointer to the top element of the stack.
Example of valid
strings :
abcb
a
aabbcbb
aa
Example of Invalid
strings:
aabcaa
b
L= {wcwR
| w Є {a,b}*
} (Where wR
is the reverse of w)
a b a c a b
a
𝒄
𝒂
𝒃
𝒂
𝒂
𝒃
𝒂
Algorithm: RECOGNIZE
Input String: a b c
b a □
Charact
er
Scanne
d
Stack
Content
c
1. [Initialize stack by placing
a letter ‘c’ on the top]
TOP  0
S [TOP] ← ‘c’
0
2. [Get and PUSH symbols until
either c’ or blank is
encountered]
NEXT ← NEXTCHAR (STRING)
Repeat while NEXT ≠ ‘c’
If NEXT = ‘ ‘
Then Write (‘Invalid
String’)
Exit
Else Call PUSH (S, TOP,
NEXT)
NEXT ← NEXTCHAR
(STRING)
a ca
b cab
c cab
NEXT
1
Algorithm: RECOGNIZE
b ca
a c
3. Scan characters following ‘c’;
Compare them to the characters on
stack
Repeat While S[TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING)
X ← POP (S, TOP)
If NEXT ≠ X
Then Write(‘Invalid String’)
Exit
2
Charact
er
Scanne
d
Stack
Content
c
0
a ca
b cab
c cab
1
Input String: a b c
b a □
NEXT
4. [Next symbol must be blank]
NEXT ← NEXTCHAR (STRING)
If NEXT = ‘ ‘
Then Write (‘VALID STRING’)
Else Write (‘INVALID STRING’) □
Algorithm: RECOGNIZE
1. [Initialize stack by placing a
letter ‘c’ on the top]
TOP  0
S [TOP] ← ‘c’
2. [Get and PUSH symbols until
either ‘c’ or blank is
encountered]
NEXT ← NEXTCHAR (STRING)
Repeat while NEXT ≠ ‘c’
If NEXT = ‘ ‘
Then Write (‘Invalid
String’)
Exit
Else Call PUSH (S, TOP,
NEXT)
NEXT ← NEXTCHAR
(STRING)
3. [Scan characters following ‘c’;
Compare them to the characters
on stack]
Repeat While S [TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING)
X ← POP (S, TOP)
If NEXT ≠ X
Then Write(‘INVALID STRING’)
Exit
4. [Next symbol must be blank]
NEXT ← NEXTCHAR (STRING)
If NEXT = ‘ ‘
Then Write (‘VALID STRING’)
Else Write (‘INVALID STRING’)
5. [Finished]
Exit
Algorithm : RECOGNIZE
 Write an algorithm to determine if an input character string is of the form ai
bi
where i>=1
 i.e. number of a should be equal to no of b
Algorithm to find factorial using recursion
 Given integer number N
 This algorithm computes factorial of N.
 Stack S is used to store an activation record associated with each recursive call.
 TOP is a pointer to the top element of stack S.
 Each activation record contains the current value of N and the current return
address RET_ADDE.
 TEMP_REC is also a record which contains two variables PARAM & ADDRESS.
 Initially return address is set to the main calling address. PARAM is set to
initial value N.
Trace of Algorithm FACTORIAL, N=2
Enter Level
1
(main call)
Step 1: PUSH (S,0,(N=2, main
address))
Step 2: N!=0
PARAM  N-1 (1), ADDR 
Step 3
2
Main
Address
TOP
Enter Level 2
(first recursive
call)
Step 1: PUSH (S,1,(N=1, step 3))
Step 2: N!=0
PARAM  N-1 (3), ADDR 
Step 3
2
Main
Address
1
Step
3
TOP
Enter Level 3
(second
recursive
call)
Step 1: PUSH (S,2,(N=0, step 3))
Step 2: N=0
FACTORIAL  1
2
Main
Address
1
Step
3
0
Step
3
TOP
Step 4: POP(A,3)
GO TO Step 3 2
Main
Address
1
Step
3
TOP
Level
Number
Description Stack
Content
Trace of Algorithm FACTORIAL, N=2
Return to
Level 2
Step 3: FACTORIAL  1*1
Step 4: POP (A,2)
GO TO Step 3
2
Main
Address
TOP
Return to
Level 1
Step 3: FACTORIAL  2*1
Step 4: POP (A,1)
GO TO Main Address
TOP = 0
Level
Number
Description Stack
Content
Algorithm: FACTORIAL
1. [Save N and return Address]
CALL PUSH (S, TOP, TEMP_REC)
2. [Is the base criterion found?]
If N=0
then FACTORIAL  1
GO TO Step 4
Else PARAM  N-1
ADDRESS  Step 3
GO TO Step 1
3. [Calculate N!]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP_REC  POP(S,TOP)
(i.e. PARAM  N, ADDRESS  RET_ADDR)
GO TO ADDRESS
Ad

More Related Content

Similar to Stack Data Structure Intro and Explanation (20)

Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)
lahariit406
 
Prefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptxPrefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptx
rtiwary190801
 
Stack and queue
Stack and queueStack and queue
Stack and queue
Shakila Mahjabin
 
Data structures
Data structures Data structures
Data structures
Rokonuzzaman Rony
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
Ain-ul-Moiz Khawaja
 
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
Soumen Santra
 
stack-Intro.pptx
stack-Intro.pptxstack-Intro.pptx
stack-Intro.pptx
DEEPAK948083
 
Stack
StackStack
Stack
Swarup Boro
 
Data Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptxData Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptx
msoomar8611
 
Lecture_04.2.pptx
Lecture_04.2.pptxLecture_04.2.pptx
Lecture_04.2.pptx
RockyIslam5
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
Afaq Mansoor Khan
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
Rashmiranja625
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
kumarkaushal17
 
Stack application
Stack applicationStack application
Stack application
Student
 
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.pptStack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
aamirali1061a
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdf
pristiegee
 
week9-prefixinfixandpostfixnotations-191013065821.pptx
week9-prefixinfixandpostfixnotations-191013065821.pptxweek9-prefixinfixandpostfixnotations-191013065821.pptx
week9-prefixinfixandpostfixnotations-191013065821.pptx
ssusere3b1a2
 
Stacks and queues using aaray line .pptx
Stacks and queues using aaray line .pptxStacks and queues using aaray line .pptx
Stacks and queues using aaray line .pptx
ramkumar649780
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
Mandeep Singh
 
Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)
lahariit406
 
Prefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptxPrefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptx
rtiwary190801
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
Soumen Santra
 
Data Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptxData Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptx
msoomar8611
 
Lecture_04.2.pptx
Lecture_04.2.pptxLecture_04.2.pptx
Lecture_04.2.pptx
RockyIslam5
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
Afaq Mansoor Khan
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
Rashmiranja625
 
Stack application
Stack applicationStack application
Stack application
Student
 
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.pptStack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
aamirali1061a
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdf
pristiegee
 
week9-prefixinfixandpostfixnotations-191013065821.pptx
week9-prefixinfixandpostfixnotations-191013065821.pptxweek9-prefixinfixandpostfixnotations-191013065821.pptx
week9-prefixinfixandpostfixnotations-191013065821.pptx
ssusere3b1a2
 
Stacks and queues using aaray line .pptx
Stacks and queues using aaray line .pptxStacks and queues using aaray line .pptx
Stacks and queues using aaray line .pptx
ramkumar649780
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
Mandeep Singh
 

Recently uploaded (20)

Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Ad

Stack Data Structure Intro and Explanation

  • 2. Stack  A linear list which allows insertion and deletion of an element at one end only is called stack.  The insertion operation is called as PUSH and deletion operation as POP.  The most accessible elements in stack is known as top.  The elements can only be removed in the opposite orders from that in which they were added to the stack.  Such a linear list is referred to as a LIFO (Last In First Out) list. … … TOP Insertio n Deletion A B C
  • 3. Stack Cont…  A pointer TOP keeps track of the top element in the stack.  Initially, when the stack is empty, TOP has a value of “-1”.  Each time a new element is inserted in the stack, the pointer is incremented by “one” before, the element is placed on the stack.  The pointer is decremented by “one” each time a deletion is made from the stack.
  • 4. Applications of Stack  Recursion ( https://cdn-media-1.freecodecamp.org/images/1*fsYHEgadIdn0fJt-cBXDHQ.gif)  Keeping track of function calls  Evaluation of expressions  Reversing characters  Servicing hardware interrupts  Solving combinatorial problems using backtracking  Expression Conversion (Infix to Postfix, Infix to Prefix)  Game Playing (Chess)  Microsoft Word (Undo / Redo)  Compiler – Parsing syntax & expression  Finding paths
  • 5. Procedure : PUSH (S, TOP, X)  This procedure inserts an element X to the top of a stack.  Stack is represented by a vector S containing N elements.  A pointer TOP represents the top element in the stack. 1. [Check for stack overflow] If TOP ≥ N-1 Then write (‘STACK OVERFLOW’) Return 2. [Increment TOP] TOP ← TOP + 1 3. [Insert Element] S[TOP] ← X 4. [Finished] Return S Stack is empty, TOP = -1, N=3 PUSH(S, TOP, 10) TOP = 0 10 PUSH(S, TOP, 8) TOP = 1 8 PUSH(S, TOP, - 5) TOP = 2 -5 PUSH(S, TOP, 6) Overflow
  • 6. Function : POP (S, TOP)  This function removes & returns the top element from a stack.  Stack is represented by a vector S containing N elements.  A pointer TOP represents the top element in the stack. 1. [Check for stack underflow] If TOP = -1 Then write (‘STACK UNDERFLOW’) Return (0) 2. [Decrement TOP] TOP ← TOP - 1 3. [Return former top element of stack] Return(S[TOP + 1]) S 10 8 -5 POP(S, TOP) TOP = 2 TOP = 1 POP(S, TOP) TOP = 0 POP(S, TOP) TOP = - 1 POP(S, TOP) Underflow
  • 7. Function : PEEP (S, TOP, I)  This function returns the value of the Ith element from the TOP of the stack. The element is not deleted by this function.  Stack is represented by a vector S containing N elements. 1. [Check for stack underflow] If TOP-I+1 ≤ -1 Then write (‘STACK UNDERFLOW’) Return (0) 2. [Return Ith element from top of the stack] Return(S[TOP–I+1]) S 10 8 -5 TOP = 2 PEEP (S, TOP, 2) 8 PEEP (S, TOP, 3) 10 PEEP (S, TOP, 4) Underflo w
  • 8. PROCEDURE : CHANGE (S, TOP, X, I)  This procedure changes the value of the Ith element from the top of the stack to X.  Stack is represented by a vector S containing N elements. 1. [Check for stack underflow] If TOP-I+1 ≤ -1 Then write (‘STACK UNDERFLOW’) Return 2. [Change Ith element from top of the stack] S[TOP–I+1] ← X 3. [Finished] Return S 10 8 -5 TOP = 2 CHANGE (S, TOP, 50, 2) 50 CHANGE (S, TOP, 9, 3) 9 CHANGE (S, TOP, 25, 8) Underflow
  • 9. Polish Expression & their Compilation  Evaluating Infix Expression a + b * c + d * e 1 2 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: Operator, Operand, Operand  Postfix Expression: Operand, Operand, Operator (a + b) * (c + d) * e
  • 10. 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.
  • 11. Polish Notation Sr. Infix Postfix Prefix 1 a 2 a + b 3 a + b + c 4 a + (b + c) 5 a + (b * c) 6 a * (b + c) 7 a * b * c a a a b + + a b a + b + c a + b + c (ab+)+ c (ab+) c + a b + c + a b + c + + + a b c a b c + + + a + b c a b c * + +a * b c a b c + * * a + b c a b *c* ** a b c
  • 12. Finding Rank of any Expression E = ( A + B * C / D - E + F / G / ( H + I )) 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) Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1 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
  • 13. Infix and postfix  Conventional notation is called infix notation.  Parentheses are required to specify the order of the operations. For example: a * b + c  Postfix notation (also known as reverse Polish notation) eliminates the need for parentheses.  There are no precedence rules to learn, and parentheses are never needed.
  • 14. Infix to postfix Conversion Let us use a stack 1. When an operand is read, output it 2. When an operator is read • Pop until the top of the stack has an element of lower precedence • Then push it 3. When ) is found, pop until we find the matching ( 4. ( has the lowest precedence when in the stack but has the highest precedence when in the input 5. When we reach the end of input, pop until the stack is empty
  • 15. Infix to postfix Conversion Symbol Input precedence function (F) Stack precedence function (G) Rank function (R) +, - 1 2 -1 *, / 3 4 -1 ^ 6 5 -1 Variabl es 7 8 1 ( 9 0 -
  • 16. infixVect postfixVect ( a + b - c ) * d – ( e + f ) Infix to postfix conversion Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 17. infixVect postfixVect a + b - c ) * d – ( e + f ) ( stackVect Infix to postfix conversion Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 18. infixVect postfixVect + b - c ) * d – ( e + f ) ( a Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 19. infixVect postfixVect b - c ) * d – ( e + f ) ( a + Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 20. infixVect postfixVect - c ) * d – ( e + f ) ( a b + Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 21. infixVect postfixVect c ) * d – ( e + f ) ( a b + - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 22. infixVect postfixVect ) * d – ( e + f ) ( a b + c - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 23. infixVect postfixVect * d – ( e + f ) a b + c - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 24. infixVect postfixVect d – ( e + f ) a b + c - * Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 25. infixVect postfixVect – ( e + f ) a b + c - d * Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 26. infixVect postfixVect ( e + f ) a b + c – d * - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 27. infixVect postfixVect e + f ) a b + c – d * - ( Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 28. infixVect postfixVect + f ) a b + c – d * e - ( Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 29. infixVect postfixVect f ) a b + c – d * e - ( + Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 30. infixVect postfixVect ) a b + c – d * e f - ( + Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 31. infixVect postfixVect a b + c – d * e f + - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 32. infixVect postfixVect a b + c – d * e f + - Infix to postfix conversion stackVect Sym Prece dence +, - 2 *, / 4 ^ 5 Varia bles 8 ( 0 ) -
  • 33. 3 + 4 * 5 / 6 Exercise (300 + 23) * (43 - 21) / (84 + 7) (4 + 8) * (6 - 5) / ((3 – 2) * (2 + 2)) ((a + b) – c * d + (t * 4)) (((ab + t – 6) * 5) – (5 + x) / z) Symbol Stack precedenc e function (G) +, - 2 *, / 4 ^ 5 Variabl es 8 ( 0 ) -
  • 34. 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 the 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.
  • 35. Infix to postfix Conversion Symbol Input precedence function (F) Stack precedence function (G) Rank function (R) +, - 1 2 -1 *, / 3 4 -1 ^ 6 5 -1 Variabl es 7 8 1 ( 9 0 -
  • 36. Input Symbol Content of stack Reverse polish expression Rank (( a + b ^ c ^ d )) NEXT 1. [Initialize Stack] TOP  0 S[TOP] ← ‘(’ ( 2. [Initialize output string and rank count] POLISH  ‘’ RANK  0 0 3. [Get first input symbol] NEXT  NEXTCHAR(INFIX) (
  • 37. Input Symbol Content of stack Reverse polish expression Rank ( a + b ^ c ^ d ) NEXT ( 0 ( 4. [Translate the infix expression] Repeat thru step 7 while NEXT!= ‘)‘ 5. [Remove symbols with greater precedence from stack] IF TOP < 0 Then write (‘INVALID’) EXIT Repeat while G(S[TOP]) > F(NEXT) TEMP  POP (S, TOP) POLISH  POLISH O TEMP RANK  RANK + R(TEMP) IF RANK < 0 Then write (‘INVALID’) EXIT 6. [Are there matching parentheses] IF G(S[TOP]) != F(NEXT) Then call PUSH (S,TOP, NEXT) Else POP (S,TOP) 7. [Get next symbol] NEXT  NEXTCHAR(INFIX) (( 0 a ((a 0 + (( a 1 ((+ b ((+b a 1 ^ ((+ ab 2 ((+^ c ((+^c ab 2 ^ ((+^ abc 3 ((+^^ d ((+^^d abc 3 ) (( abcd^^+ 1 (
  • 38. 1. [Initialize Stack] TOP  0 S[TOP] ← ‘(’ 2. [Initialize output string and rank count] POLISH  ‘’ RANK  0 3. [Get first input symbol] NEXT  NEXTCHAR(INFIX) 4. [Translate the infix expression] Repeat thru step 7 while NEXT != ‘)‘ 5. [Remove symbols with greater precedence from stack] IF TOP < 0 Then write (‘INVALID’) EXIT Repeat while G(S[TOP]) > F(NEXT) TEMP  POP (S, TOP) POLISH  POLISH O TEMP RANK  RANK + R(TEMP) IF RANK < 0 Then write (‘INVALID’) EXIT 6. [Are there matching parentheses] IF G(S[TOP]) != F(NEXT) Then call PUSH (S,TOP, NEXT) Else POP (S,TOP) 7. [Get next symbol] NEXT  NEXTCHAR(INFIX) 8. [Is the expression valid] IF TOP != -1 OR RANK != 0 Then write (‘INVALID‘) Else write (‘VALID’) Symbol IPF (F) SPF (G) RF (R) +, - 1 2 -1 *, / 3 4 -1 ^ 6 5 -1 Variables 7 8 1 ( 9 0 - ) 0 - -
  • 39. 2 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 1 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. 3 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. 4 Infix: ( a + b ^ c ^ d ) * ( e + f / d ) Symbol Input precedence function (F) Stack precedence function (G) Rank function (R) +, - 1 2 -1 *, / 3 4 -1 ^, $ 6 5 -1 Variable 7 8 1 Postfix: a b c ^ d ^ + e f d / + *
  • 40. Perform following operations  Convert the following infix expression to postfix. Show the stack contents.  A$B-C*D+E$F/G  A+B–C*D*E$F$G  a+b*c-d/e*h  ((a+b^c^d)*(e+f/d))  Convert the following infix expression to prefix.  A + B – C * D * E ^ F ^ G  Step 1: Reverse infix input string  Step 2: Convert reverse infix of step 1 into postfix  Step 3: Reverse postfix expression of step 2 Symbol Input precedence function (F) Stack precedence function (G) Rank function (R) +, - 1 2 -1 *, / 3 4 -1 ^, $ 6 5 -1 Variable s 7 8 1 ( 9 0 - ) 0 - - AB$CD*-EF$G/+ AB+CD*EF$G$*- abc*+de/h*- abc^d^+efd/+* G ^ F ^ E * D * C – B + A G F ^ E ^ D * C – B * A+ +A * B – C * D ^ E ^ F G
  • 41. 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 be available for use as an operand for the next operator.
  • 42. Evaluation of postfix expression Evaluate Expression: 5 6 2 - + Empty Stack Read 5, is it operand? PUSH 5 Read 6, is it operand? PUSH 6 Read 2, is it operand? PUSH 2 Read – , is it operator? POP two symbols and perform operation and PUSH result Operan d 1 Operan d 2 – 5 4 Read + , is it operator? POP two symbols and perform operation and PUSH result Operan d 1 Operan d 2 + Read next symbol, if it is end of string, POP answer from Stack Answe r 9
  • 43. Algorithm: EVALUATE_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.
  • 44. Algorithm: EVALUATE_POSTFIX 1. [Initialize Stack] TOP  -1 VALUE  0 2. [Evaluate the postfix expression] Repeat until last character TEMP  NEXTCHAR (POSTFIX) 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) 3. [Return answer from stack] Return (POP (S, TOP))
  • 45. Evaluation of postfix expression Evaluate Expression: 5 4 6 + * 4 9 3 / + * Evaluate Expression: 7 5 2 + * 4 1 1 + / - Evaluate Expression: 12, 7, 3, -, /, 2, 1, 5, +, *, + 350 47 15
  • 46. Algorithm: EVALUATE_PREFIX  Given an input string PREFIX representing prefix expression.  This algorithm evaluates prefix 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.
  • 47. Algorithm: EVALUATE_PREFIX 1. [Initialize Stack] TOP  -1 VALUE  0 2. [Evaluate the prefix expression] Repeat from last character up to first TEMP  NEXTCHAR (PREFIX) If TEMP is DIGIT Then PUSH (S, TOP, TEMP) Else OPERAND1  POP (S, TOP) OPERAND2  POP (S, TOP) VALUE  PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP) PUSH (S, POP, VALUE) 3. [Return answer from stack] Return (POP (S, TOP))
  • 48. Recursion A procedure that contains a procedure call to itself or a procedure call to second procedure which eventually causes the first procedure to be called is known as recursive procedure. Two important conditions for any recursive procedure Each time a procedure calls itself it must be nearer in some sense to a solution. 1 There must be a decision criterion for stopping the process or computation. 2 Two types of recursion This is recursive defined function. E.g. Factorial function Primitive Recursion This is recursive use of procedure. E.g. Find GCD of given two numbers Non-Primitive Recursion
  • 49. The Towers of Hanoi • In the great temple of Brahma in Benares, on a brass plate under the dome that marks the center of the world, there are 64 disks of pure gold that the priests carry one at a time between these diamond needles according to Brahma's immutable law: • No disk may be placed on a smaller disk. In the begging of the world all 64 disks formed the Tower of Brahma on one needle. Now, however, the process of transfer of the tower from one needle to another is in mid course. • When the last disk is finally in place, once again forming the Tower of Brahma but on a different needle, then will come the end of the world and all will turn to dust.
  • 50. Is the End of the World Approaching? • 64 gold discs • Given 1 move a second • Problem complexity 2n 584,942,417,355 years five hundred eighty-four billion nine hundred forty-two million four hundred seventeen thousand three hundred fifty-five years
  • 51. The Towers of Hanoi --- A Stack-based Application • GIVEN: three poles • a set of discs on the first pole, discs of different sizes, the smallest discs at the top • GOAL: move all the discs from the left pole to the right one. • CONDITIONS: only one disc may be moved at a time. • A disc can be placed either on an empty pole or on top of a larger disc.
  • 60. Towers of Hanoi – Implementation using ‘C’ void TOH(int n,char x,char y,char z) { if(n>0) { count++; TOH(n-1,x,z,y); printf("n%c to %c",x,y); TOH(n-1,z,y,x); } } int main() { int n=3; TOH(n,'A','B','C'); printf(“nTotal steps are %d",count); } #include<stdio.h> int count=0;
  • 62. Algorithm: RECOGNIZE Write an algorithm which will check that the given string belongs to following grammar or not. L= {wcwR | w Є {a,b}* } (Where wR is the reverse of w) • Given an input string named STRING on the alphabet {a, b, c} which contains a blank in its rightmost character position. • Function NEXTCHAR returns the next symbol in STRING. • This algorithm determines whether the contents of STRING belong to the above language. • The vector S represents the stack and TOP is a pointer to the top element of the stack. Example of valid strings : abcb a aabbcbb aa Example of Invalid strings: aabcaa b
  • 63. L= {wcwR | w Є {a,b}* } (Where wR is the reverse of w) a b a c a b a 𝒄 𝒂 𝒃 𝒂 𝒂 𝒃 𝒂
  • 64. Algorithm: RECOGNIZE Input String: a b c b a □ Charact er Scanne d Stack Content c 1. [Initialize stack by placing a letter ‘c’ on the top] TOP  0 S [TOP] ← ‘c’ 0 2. [Get and PUSH symbols until either c’ or blank is encountered] NEXT ← NEXTCHAR (STRING) Repeat while NEXT ≠ ‘c’ If NEXT = ‘ ‘ Then Write (‘Invalid String’) Exit Else Call PUSH (S, TOP, NEXT) NEXT ← NEXTCHAR (STRING) a ca b cab c cab NEXT 1
  • 65. Algorithm: RECOGNIZE b ca a c 3. Scan characters following ‘c’; Compare them to the characters on stack Repeat While S[TOP] ≠ ‘c’ NEXT ← NEXTCHAR (STRING) X ← POP (S, TOP) If NEXT ≠ X Then Write(‘Invalid String’) Exit 2 Charact er Scanne d Stack Content c 0 a ca b cab c cab 1 Input String: a b c b a □ NEXT 4. [Next symbol must be blank] NEXT ← NEXTCHAR (STRING) If NEXT = ‘ ‘ Then Write (‘VALID STRING’) Else Write (‘INVALID STRING’) □
  • 66. Algorithm: RECOGNIZE 1. [Initialize stack by placing a letter ‘c’ on the top] TOP  0 S [TOP] ← ‘c’ 2. [Get and PUSH symbols until either ‘c’ or blank is encountered] NEXT ← NEXTCHAR (STRING) Repeat while NEXT ≠ ‘c’ If NEXT = ‘ ‘ Then Write (‘Invalid String’) Exit Else Call PUSH (S, TOP, NEXT) NEXT ← NEXTCHAR (STRING) 3. [Scan characters following ‘c’; Compare them to the characters on stack] Repeat While S [TOP] ≠ ‘c’ NEXT ← NEXTCHAR (STRING) X ← POP (S, TOP) If NEXT ≠ X Then Write(‘INVALID STRING’) Exit 4. [Next symbol must be blank] NEXT ← NEXTCHAR (STRING) If NEXT = ‘ ‘ Then Write (‘VALID STRING’) Else Write (‘INVALID STRING’) 5. [Finished] Exit
  • 67. Algorithm : RECOGNIZE  Write an algorithm to determine if an input character string is of the form ai bi where i>=1  i.e. number of a should be equal to no of b
  • 68. Algorithm to find factorial using recursion  Given integer number N  This algorithm computes factorial of N.  Stack S is used to store an activation record associated with each recursive call.  TOP is a pointer to the top element of stack S.  Each activation record contains the current value of N and the current return address RET_ADDE.  TEMP_REC is also a record which contains two variables PARAM & ADDRESS.  Initially return address is set to the main calling address. PARAM is set to initial value N.
  • 69. Trace of Algorithm FACTORIAL, N=2 Enter Level 1 (main call) Step 1: PUSH (S,0,(N=2, main address)) Step 2: N!=0 PARAM  N-1 (1), ADDR  Step 3 2 Main Address TOP Enter Level 2 (first recursive call) Step 1: PUSH (S,1,(N=1, step 3)) Step 2: N!=0 PARAM  N-1 (3), ADDR  Step 3 2 Main Address 1 Step 3 TOP Enter Level 3 (second recursive call) Step 1: PUSH (S,2,(N=0, step 3)) Step 2: N=0 FACTORIAL  1 2 Main Address 1 Step 3 0 Step 3 TOP Step 4: POP(A,3) GO TO Step 3 2 Main Address 1 Step 3 TOP Level Number Description Stack Content
  • 70. Trace of Algorithm FACTORIAL, N=2 Return to Level 2 Step 3: FACTORIAL  1*1 Step 4: POP (A,2) GO TO Step 3 2 Main Address TOP Return to Level 1 Step 3: FACTORIAL  2*1 Step 4: POP (A,1) GO TO Main Address TOP = 0 Level Number Description Stack Content
  • 71. Algorithm: FACTORIAL 1. [Save N and return Address] CALL PUSH (S, TOP, TEMP_REC) 2. [Is the base criterion found?] If N=0 then FACTORIAL  1 GO TO Step 4 Else PARAM  N-1 ADDRESS  Step 3 GO TO Step 1 3. [Calculate N!] FACTORIAL N * FACTORIAL 4. [Restore previous N and return address] TEMP_REC  POP(S,TOP) (i.e. PARAM  N, ADDRESS  RET_ADDR) GO TO ADDRESS