Transcript Lecture 20

CSC 205
Programming II
Lecture 20
Postfix Expressions
Recap: Stack

Stack features



Stack operations




Orderly linear structure
Access from one side only – top item
Push – add an item to top
Pop – remove the top item
Peek – get the content of the top item
Implementations and trade-offs
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
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
*+342
Postfix: operator following operands
234+*
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
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
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
Sample Expression 1
–fully parenthesized
(a – ((b + (c * d)) / e))
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)
Sample Expression 2
– parenthesized as needed
a – (b + c * d) / e
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)