CS241: Spring 2017 -- Expressions

  1. Quiz feedback: improvement! This week? Algorithms for evaluating infix and postfix expressions.
  2. An ArrayList of Strings (the code I write to remind myself how ArrayList works)
  3. Two new data structures; both lists with constraints (!?): stack (compilers) and queue (operating systems)
  4. Designing a Queue
    1. Methods
      1. void enqueue(Foo) - adds the Foo to the tail of the list
      2. Foo dequeue() - removes and returns the Foo at the head of the list
      3. boolean isEmpty() - true if is empty!
    2. Representation
      1. array
      2. ArrayList
    3. What kind of elements will be stored(i.e. what is Foo above)?
      1. String?
      2. Object?
      3. Operand?
      4. Stackable?
      5. <T>?
  5. Example: Implementing a Queue
  6. Designing a Stack
    1. Methods
      1. void push(Foo) - adds the Foo to the tail of the list
      2. Foo pop() - removes and returns the Foo at the tail
      3. boolean isEmpty() - true if is empty!
      4. Foo top() - returns the Foo at the tail without deleting it - a convenience method
    2. Representation
      1. array
      2. ArrayList
  7. Expression evaluation
    1. Introduction to expressions: prefix, infix, and postfix
    2. Evaluating arbitrary infix expressions; not so easy!!
    3. 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
      
    4. converting infix to postfix expressions (without parentheses!):
      while (more input) {
         next = nextToken()
         if (next is operand) 
            emit next
         else {
            while (!stack.isEmpty() && (precedence(top()) >= precedence(next))) {  
               emit(pop());
            } // while
            push(next)
         } // else
      }
      
      while !stack.isEmpty()
         emit(pop())
      
    5. parentheses!
      1. Insight: parentheses promote the precedence of everything inside them above everything -- thus, when the ")" is handled, you must emit all intraparenthetic operators
      2. Treat "("'s as operators, except
        1. When you handle one, simply push it, irrespective of what's currently on the stack. It is a marker for how many operators to pop when you find the matching ")"
        2. "(" as the lowest precedence than any other operator (so any operator may be pushed on top of it)
        3. Do not emit
      3. Treat ")"'s as operators, except
        1. When you handle one, pop and emit every operator on the stack until you pop the "(".
        2. If you make its precedence higher than anything, the original loop will work except for looking for the "("
        3. Do not emit