# 40 - 00:05:23 CS61B Lecture 40 Friday May 1 2009 Expression...

This preview shows pages 1–2. Sign up to view the full content.

04/30/09 00:05:23 1 40 CS61B: Lecture 40 Friday, May 1, 2009 Expression Parsing (an application of stacks) --------------------------------------------- Arithmetic expressions can be written in prefix, infix, or postfix. Infix is the usual way of writing expressions that we’re all familiar with: 3 + 4 * 7. You’re also familiar with prefix notation from Scheme; the same expression is written + 3 * 4 7. In postfix, it’s written 3 4 7 * +. In postfix, we write an operator after its operands: 4 7 *. Each operand may itself be any postfix expression. Hence, 1 2 + 3 4 + * is an expression whose operands are 1 2 + and 3 4 +; we might parenthesize it (1 2 +) (3 4 +) *. However, unlike in infix, parentheses are never necessary. A postfix expression is easily evaluated by maintaining a stack of numbers. We read a postfix expression from left to right. When we encounter a number, we push it onto the stack. When we encounter an operator, we pop the top two numbers off the stack, perform the operation on them (using the first number popped as the _second_ operand), and push the result onto the stack. Let’s compute 2 7 5 - * 8 5 - *. | | | | | | |5| | | | | | | |5| | | | | | | --> | | --> |7| --> |7| --> |2| --> | | --> |8| --> |8| --> |3| --> | | | | 2 |2| 7 |2| 5 |2| - |2| * |4| 8 |4| 5 |4| - |4| * |12| --- --- --- --- --- --- --- --- --- ---- Here’s code that performs one such operation. For brevity, the division operator and all error checking are omitted. public static void operate(Stack numStack, char operator) throws StackEmptyException { // Retrieve the operands from the stack. int operand2 = ((Integer) numStack.pop()).intValue(); int operand1 = ((Integer) numStack.pop()).intValue(); System.out.print(operator + " "); // Perform the operation and push the result on the number stack. switch (operator) {

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 02/21/2010 for the course CS 61B taught by Professor Canny during the Spring '01 term at Berkeley.

### Page1 / 2

40 - 00:05:23 CS61B Lecture 40 Friday May 1 2009 Expression...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online