08-complexity

# 08-complexity - CSE143 Lecture8 MoreStacksandQueues...

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

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/

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

View Full Document
2 Stack/queue exercise 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
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 2 5 4 4 2 5 * 8 5 + 13 7 7 13 - 6

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

View Full Document
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);
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 18

08-complexity - CSE143 Lecture8 MoreStacksandQueues...

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

View Full Document
Ask a homework question - tutors are online