CS136, Lecture 15

    1. Applications of stacks:
      1. Running mazes
      2. Evaluation of arithmetic expressions.
      3. Run-time stacks on computers

Applications of stacks:

Running mazes

Keep cells on path from start on a stack. Mark cells when visit them.

See Maze program on-line.

  public void runMaze() 
  {
    success = false;                 // No solution yet
    
    current = start;                 // Initialize current to start
    current.visit();
    
    path = new StackList();          // Create new path
    path.push(current);              // with start on it
    
    while (!path.empty() && !success)   
      {                              // Search until success or run out of cells
         current = nextUnvisited();  // Get new cell to visit
                
         if (current != null) {      // If unvisited cell, 
            current.visit();         // move to it &
            path.push(current);      // push it onto path
            success = current.equals(finish); // Done yet?
          } 
          else        // No neighbors to visit so back up
          {           // Pop off last cell visited
             current = (Position)path.pop();   
             if (!path.empty())      // If path non-empty take last 
                                     //  visited as new current
                current = (Position)path.peek();
          }
      }
  }
Marking of cells and use of stack keeps from searching around in circles and yet not missing any possible paths.

Evaluation of arithmetic expressions.

Some machines have stack based machine language instructions.

E.g. PUSH, POP, ADD (pop off top two elements from stack, add them and push result back onto stack), SUB, MULT, DIV, etc.

Ex. Translate X * Y + Z * W to:

    PUSH X
    PUSH Y
    MULT
    PUSH Z
    PUSH W
    MULT
    ADD
Trace result if X = 2, Y = 7, Z = 3, W = 4.

How do you generate this code?

Write expression in postfix form: operator after operands

E.g. 2 + 3 -> 2 3 +

General algorithm to convert:

  1. Write expression fully parenthesized.

  2. Recursively move operator after operands, dropping parentheses when done.
E.g.

X * Y + Z * W -> (X * Y) + (Z * W) -> (X Y *) (Z W *) + -> X Y * Z W * +

Note parentheses no longer needed. Corresponds to reverse Polish calculator.

Once in postfix, easy to generate code as follow:

Therefore above expression compiled as shown earlier: PUSH X, PUSH Y, MULT, ...

Straightforward to write a computer program using stacks to use these instructions (or even the original postfix expression) to calculate values of arithmetic expressions.

On such a calculator, "PUSH" key is usually labelled ENTER.

Also usually only first operand must be "ENTER"ed. Rest automatically "ENTER"ed after type and then hit operator key.

This will be your next homework assignment!

Interestingly, algorithm to convert expression to postfix form can either be done recursively (as above) or using a stack.

Notice all operands appear in same order as started - only operations move. Commands to transform above expression (working on it from left to right):

    OUTPUT X
    PUSH *
    OUTPUT Y
    POP and OUTPUT operator
    PUSH +
    OUTPUT Z
    PUSH *
    OUTPUT W
    POP and OUTPUT operator
    POP and OUTPUT operator
(Other rules - "(" is always pushed onto stack, ")" causes operators to be popped and output until pop off topmost "(" on stack. )

Big question: When do you push one operator on top of another and when do you pop off topmost operator before pushing on new one?

Answer given in terms of precedence of operators!

Bring answer to class Monday!


Run-time stacks on computers

All computers use a run-time stack in order to keep track of procedure, function, or method invocations.

Programs which use stacks can often be rewritten to simply use recursion (since recursion deals with an implicit stack. Hence the maze-running program can be rewritten as follows, where caller is responsible for setting success to false and current to start originally:

public void runMaze() 
{
    Position origCurrent = current;     // Save orig value  
    current.visit();
    success = current.equals(finish);   // Are we finished?
        
    while (current != null && !success)     
    {                   // Search until success or run out of cells
        current = nextUnvisited();  // Find new cell to visit
        if (current != null)
        {
            current.visit();
            runMaze();  // Try solving maze from new current
            current = origCurrent;      // reset to try again
        }
    }
}