Download presentation
Presentation is loading. Please wait.
Published byDoreen Collins Modified over 9 years ago
1
CSC 205 Programming II Postfix Expressions
2
Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations Push – add an item to top Pop – remove the top item Peek – get the content of the top item Implementations and trade-offs
3
Array-based Implementation Instance variables needed Collection of data – Object[] items Two auxiliary variables Number of items on stack – int numItems Stack capacity – int CAPACITY Selected methods pop popAll
4
Arithmetic Expressions Three possible orders Infix: operator in between operands 2 * (3 + 4) Widely used in normal presentation Parentheses needed to remove ambiguity Prefix: operator proceeds operands * + 3 4 2 Postfix: operator following operands 2 3 4 + *
5
Evaluating Expressions Infix 2 * (3 + 4) 2 * (3 + 4) 2 * 7 14 Prefix * + 3 4 2 * + 3 4 2 * 7 2 14 Postfix 2 3 4 + * 2 3 4 + * 2 7 * 14
6
Evaluating Postfix Expressions Using Stack Assumptions Correct postfix expression With arithmetic operators +, -, *, and / only The algorithm Initialize a stack Read the next input while there is one If (the next input is a number) Push it onto the stack Else Pop two numbers off the stack Carry out the calculation & push the result onto the stack
7
Converting Infix to Postfix Notation It’s easier to evaluate postfix expressions No need for a separate stack for operators: an operator is consumed when encountered Infix expressions can be converted into equivalent postfix ones then be evaluated Assumptions Correct infix expression +, -, *, and / only
8
Sample Expression 1 –fully parenthesized (a – ((b + (c * d)) / e))
9
Converting Infix to Postfix Notation – when fully parenthesized Initialize a stack (for operators and parentheses) Read the next input while there is one If (the next input is a left parenthesis) Push it onto the stack Else if (the next input is a number) Write it to the output Else if (the next input is an operator) Push it onto the stack Else Pop and output the top item (an operator) Pop and discard the top item (a left parenthesis)
10
Sample Expression 2 – parenthesized as needed a – (b + c * d) / e
11
Converting Infix to Postfix Notation – using precedence rules Initialize a stack (for operators and parentheses) Read the next input while there is one If (the next input is a left parenthesis) Push it onto the stack Else if (the next input is a number) Write it to the output Else if (the next input is an operator) Pop and print operators off the stack until Stack become empty The next item is a left parenthesis The next item is an operator of lower precedence Push the new operator onto stack Else Pop and output the top item (an operator) Pop and discard the top item (a left parenthesis)
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.