08-complexity - CSE 143 Lecture 8 More Stacks and Queues;...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 143 Lecture 8 More Stacks and Queues; Complexity (Big-Oh) reading: 13.1 - 13.3 slides created by Marty Stepp http://www.cs.washington.edu/143/
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 Stack/queue exercise •A postfix expression is a mathematical expression but with the operators written after the operands rather than before. 1 + 1 becomes 1 1 + 1 + 2 * 3 + 4 becomes 1 2 3 * + 4 + – supported by many kinds of fancy calculators – never need to use parentheses – never need to use an = character to evaluate on a calculator • Write a method postfixEvaluate that accepts a postfix expression string, evaluates it, and returns the result. – All operands are integers; legal operators are + , - , * , and / postFixEvaluate("5 2 4 * + 7 -") returns 6
Background image of page 2
3 Postfix algorithm • The algorithm: Use a stack – When you see an operand, push it onto the stack. – When you see an operator: • pop the last two operands off of the stack. • apply the operator to them. • push the result onto the stack. – When you're done, the one remaining stack element is the result. "5 2 4 * + 7 -" 5 5 2 5 2 4 5 2 4 * 5 8 + 13 7 13 7 - 6
Background image of page 3

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

View Full DocumentRight Arrow Icon
Exercise solution // Evaluates the given prefix expression and returns its result. // Precondition: string represents a legal postfix expression public static int postfixEvaluate(String expression) { Stack<Integer> s = new Stack<Integer>(); Scanner input = new Scanner(expression); while (input.hasNext()) { if (input.hasNextInt()) { // an operand (integer) s.push(input.nextInt()); } else { // an operator String operator = input.next(); int operand2 = s.pop() ; int operand1 = s.pop() ; if (operator.equals("+")) { s.push(operand1 + operand2); } else if (operator.equals("-")) { s.push(operand1 - operand2);
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/04/2011 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

Page1 / 18

08-complexity - CSE 143 Lecture 8 More Stacks and Queues;...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online