CS 136 - Lecture 18

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

Applications of stacks

Running mazes

  public void runMaze() 
    success = false;                 // No solution yet
    current = start;                 // Initialize current to start
    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();

Evaluation of arithmetic expressions

Some machines have stack based machine language instructions.

Example. 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
    PUSH Z
    PUSH W
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 +

Representing arithmetic expressions:

General algorithm to convert to postfix notation:
  1. Write expression fully parenthesized.
  2. Recursively move operator after operands, dropping parentheses when done.

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

Note: in Polish notation parentheses no longer needed. Corresponds to reverse Polish calculator.

Once in postfix, easy to generate code as follows:

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.

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):

    PUSH *
    POP and OUTPUT operator
    PUSH +
    PUSH *
    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!

Run-time stacks on computers

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

Programs that 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 static void runMaze() 
    Position origCurrent = current;     // Save orig value  
    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)
            runMaze();  // Try solving maze from new current
            current = origCurrent;      // reset to try again