Unit-2
Linear Data
Structure Stack
Data Structures (DS)
GTU # 3130702
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.
… …
TO
P
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 “zero”.
🞂 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
🞂 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
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 = 0,
N=3
PUSH(S, TOP,
10)
TOP =
1
10
PUSH(S, TOP,
8)
TOP =
2
8
PUSH(S, TOP, -
5)
TOP = 3 -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 = 0
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 = 3
TOP =
2
POP(S, TOP)
TOP =
1
POP(S, TOP)
TOP =
0
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 ≤ 0
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 = 3
PEEP (S, TOP,
2) 8
PEEP (S, TOP,
3)
1
0
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 ≤ 0
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 = 3
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
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
Convert Infix to Postfix Expression
Symbol Input precedence
function (F)
Stack precedence
function (G)
Rank function
(R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -
Input
Symbol
Content
of stack
Reverse polish
expression
Rank
( a + b ^ c ^ d ) * ( e + f / d ) )
NEX
T
1. [Initialize Stack]
TOP 1
🡨
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 ) * ( e + f / d ) )
NEX
T
( 0
(
4. [Translate the infix expression]
Repeat thru step 7
while NEXT!= ‘ ‘
5. [Remove symbols with greater precedence from
stack]
IF TOP < 1
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 <1
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
(
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
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
( a + b ^ c ^ d ) * ( e + f / d )
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
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.
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, +, *, +
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.
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
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.
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
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
TO
P
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
TO
P
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
TO
P
Step 4: POP(A,3)
GO TO Step 3 2
Main
Address
1
Step
3
TO
P
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
TO
P
Return to
Level 1
Step 3: FACTORIAL 2*1
🡨
Step 4: POP (A,1)
GO TO Main AddressTOP =
0
Level
Number
Description Stack
Content

More Related Content

PPTX
Stack Data Structure Intro and Explanation
PPTX
Lec5-Stack-bukc-28022024-112316am (1) .pptx
PDF
Data Structures And Algorithms(stacks queues)
PPTX
Lecture 6 data structures and algorithms
PPTX
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
PPSX
Data structure_Stack Introduction & app.
PPT
PPT
Stack in Data Structure
Stack Data Structure Intro and Explanation
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Data Structures And Algorithms(stacks queues)
Lecture 6 data structures and algorithms
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
Data structure_Stack Introduction & app.
Stack in Data Structure

Similar to Data strutcure and annalysis topic stack (20)

PPTX
5.stack
PPTX
Stack - Data Structure - Notes
PPT
358 33 powerpoint-slides_9-stacks-queues_chapter-9
PPTX
DS UNIT1_STACKS.pptx
PPT
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
PDF
PDF
Data structure lab manual
PPTX
Stack_Overview_Implementation_WithVode.pptx
PPTX
Unit 3 Stacks and Queues.pptx
PPTX
Stacks and queues using aaray line .pptx
PPTX
COMP1603 Stacks and RPN 2023 Recording (2).pptx
PPTX
Data structures
PPTX
Evaluation of prefix expression with example
PPSX
PPTX
DSA_chapter_04_Stack and data structure and Queue.pptx
PDF
Data structure and algorithm.(dsa)
PPTX
Data Structure and Algorithms by Sabeen Memon03.pptx
PPTX
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
PPTX
DS MOD2 (1) (1).pptx
5.stack
Stack - Data Structure - Notes
358 33 powerpoint-slides_9-stacks-queues_chapter-9
DS UNIT1_STACKS.pptx
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Data structure lab manual
Stack_Overview_Implementation_WithVode.pptx
Unit 3 Stacks and Queues.pptx
Stacks and queues using aaray line .pptx
COMP1603 Stacks and RPN 2023 Recording (2).pptx
Data structures
Evaluation of prefix expression with example
DSA_chapter_04_Stack and data structure and Queue.pptx
Data structure and algorithm.(dsa)
Data Structure and Algorithms by Sabeen Memon03.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
DS MOD2 (1) (1).pptx
Ad

Recently uploaded (20)

PDF
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
PPTX
statsppt this is statistics ppt for giving knowledge about this topic
PDF
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
PDF
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
PPTX
eGramSWARAJ-PPT Training Module for beginners
PPTX
Lesson-01intheselfoflifeofthekennyrogersoftheunderstandoftheunderstanded
PPTX
Business_Capability_Map_Collection__pptx
PPTX
SET 1 Compulsory MNH machine learning intro
PDF
A biomechanical Functional analysis of the masitary muscles in man
PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
PDF
©️ 02_SKU Automatic SW Robotics for Microsoft PC.pdf
PPTX
Machine Learning and working of machine Learning
PDF
CS3352FOUNDATION OF DATA SCIENCE _1_MAterial.pdf
PPTX
The Data Security Envisioning Workshop provides a summary of an organization...
PPTX
CYBER SECURITY the Next Warefare Tactics
PPTX
AI AND ML PROPOSAL PRESENTATION MUST.pptx
PPTX
Phase1_final PPTuwhefoegfohwfoiehfoegg.pptx
PPTX
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
PDF
Session 11 - Data Visualization Storytelling (2).pdf
PPT
lectureusjsjdhdsjjshdshshddhdhddhhd1.ppt
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
statsppt this is statistics ppt for giving knowledge about this topic
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
eGramSWARAJ-PPT Training Module for beginners
Lesson-01intheselfoflifeofthekennyrogersoftheunderstandoftheunderstanded
Business_Capability_Map_Collection__pptx
SET 1 Compulsory MNH machine learning intro
A biomechanical Functional analysis of the masitary muscles in man
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
©️ 02_SKU Automatic SW Robotics for Microsoft PC.pdf
Machine Learning and working of machine Learning
CS3352FOUNDATION OF DATA SCIENCE _1_MAterial.pdf
The Data Security Envisioning Workshop provides a summary of an organization...
CYBER SECURITY the Next Warefare Tactics
AI AND ML PROPOSAL PRESENTATION MUST.pptx
Phase1_final PPTuwhefoegfohwfoiehfoegg.pptx
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
Session 11 - Data Visualization Storytelling (2).pdf
lectureusjsjdhdsjjshdshshddhdhddhhd1.ppt
Ad

Data strutcure and annalysis topic stack

  • 1. Unit-2 Linear Data Structure Stack Data Structures (DS) GTU # 3130702
  • 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. … … TO P 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 “zero”. 🞂 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 🞂 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 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 = 0, N=3 PUSH(S, TOP, 10) TOP = 1 10 PUSH(S, TOP, 8) TOP = 2 8 PUSH(S, TOP, - 5) TOP = 3 -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 = 0 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 = 3 TOP = 2 POP(S, TOP) TOP = 1 POP(S, TOP) TOP = 0 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 ≤ 0 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 = 3 PEEP (S, TOP, 2) 8 PEEP (S, TOP, 3) 1 0 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 ≤ 0 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 = 3 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
  • 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. Convert Infix to Postfix Expression Symbol Input precedence function (F) Stack precedence function (G) Rank function (R) +, - 1 2 -1 *, / 3 4 -1 ^ 6 5 -1 Variables 7 8 1 ( 9 0 - ) 0 - -
  • 14. Input Symbol Content of stack Reverse polish expression Rank ( a + b ^ c ^ d ) * ( e + f / d ) ) NEX T 1. [Initialize Stack] TOP 1 🡨 S[TOP] ← ‘(’ ( 2. [Initialize output string and rank count] POLISH ‘’ 🡨 RANK 0 🡨 0 3. [Get first input symbol] NEXT NEXTCHAR(INFIX) 🡨 (
  • 15. Input Symbol Content of stack Reverse polish expression Rank ( a + b ^ c ^ d ) * ( e + f / d ) ) NEX T ( 0 ( 4. [Translate the infix expression] Repeat thru step 7 while NEXT!= ‘ ‘ 5. [Remove symbols with greater precedence from stack] IF TOP < 1 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 <1 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 (
  • 16. 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
  • 17. 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 ( a + b ^ c ^ d ) * ( e + f / d )
  • 18. 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 for the next operator.
  • 19. 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
  • 20. 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.
  • 21. 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, +, *, +
  • 22. 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.
  • 23. 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
  • 24. 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.
  • 25. 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
  • 26. 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 TO P 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 TO P 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 TO P Step 4: POP(A,3) GO TO Step 3 2 Main Address 1 Step 3 TO P Level Number Description Stack Content
  • 27. 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 TO P Return to Level 1 Step 3: FACTORIAL 2*1 🡨 Step 4: POP (A,1) GO TO Main AddressTOP = 0 Level Number Description Stack Content