CS241: Spring 2010 --Evaluating infix expressions

  1. Stacks and Queues - a quick introduction
  2. Introduction to expressions: prefix, infix, and postfix
  3. Evaluating arbitrary infix expressions; not so easy!!
  4. postfix evaluation
    while (more input) {
       next = nextToken()
       if (next is operand)
          push(next)
       else apply next to top two operands and push the result
    }
    answer is on top of the stack
    
  5. converting infix to postfix expressions:
    while (more input) {
       next = nextToken()
       if (next is operator) {
          while (!isEmpty() && precedence(top()) >= precedence(next)) {  
             emit(pop());
          } // while
          push(next)
       } // if
       else emit next
    }
    while !stack.isEmpty()
       emit(pop())
    
  6. parentheses!