CS241: Spring 2015 -- Expression evaluation

  1. List vocabulary
    1. head - first thing in the list (or, the front of the list)
    2. tail - last thing in the list (or the end of the list)
  2. Stack and Queue are restrictions of lists.
  3. Implementing a list
    1. Operations
      1. insert at tail
      2. insert at head
      3. insert in the middle (at i)
      4. remove head - delete and return head
      5. remove tail
      6. remove ith
      7. toString, isEmpty, removeAll, etc
    2. with an array
      1. Foo[] list -- the data structure
      2. int last -- where the last thing in the list is
      3. Fixed length!
      4. Implementing the various operations
    3. with an ArrayList
      1. ArrayList<Foo> list -- the data structure
      2. Automagically variable length!
      3. Implementing the various operations
  4. Designing a Stack
    1. Methods
      1. void push(Foo) - adds the Foo to the tail of the list (i.e. pushes it on top of the stack!)
      2. Foo pop() - removes and returns the Foo from the top
      3. boolean isEmpty() - true if the stack is empty!
      4. Foo top() - returns the Foo at the top without deleting it
    2. Representation
      1. array
      2. ArrayList
    3. What will be stored in the Stack (i.e. what is Foo above)?
      1. String?
      2. Object?
      3. Operand?
      4. Token?
      5. Stackable?
  5. 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())
    
  6. parentheses!
    1. Insight: parentheses promote the precedence of everything inside them above everything -- thus, must emit all intraparenthetic operators before any following operators
    2. Treat ('s as operators, except you never emit them, with the following changes
    3. "(" as the lowest precedence than any other operator (so any operator may be pushed on top of it)
    4. ")" never goes on the stack, so if you also give it the lowest precedence of anything, the while loop (in the pseudocode above) will pop and emit everything on the stack! You must modify that loop to stop when a "(" is popped (then discard it and the close paren)