CompSci-61B Lecture Topic 8
Stacks and Queues

Instructor: Prof. Robert Burns

Ref: Carrano ch.21-24 and App.C

Specializations Of Lists
stacks: LIFO (last in, first out)
queues: FIFO (first in, first out)
priority queues
deques (double-ended)

Stacks
"remove" gets most recently-added
applications:
  RPN solver
  parentheses balance

Stack Operations
push: add a value
peek: "view" most recently added value
pop: remove most recently added value
java.util.Stack class
empty, Iterable

Stack Applications
parentheses balance checking
  parse chars
  push open parens
  compare close parens to peek
    pop if match found
    else fail
reverse Polish notation (RPN) processing
  push values onto stack
  pop value(s) for unary or binary ops

Queues
"remove" gets least recently-added
applications:
  service line
  expression eval

Queue Operations
add: add a value
peek: "view" least recently added value
poll: remove least recently added value
java.util.Queue interface
java.util.LinkedList class
isEmpty, Iterable

Queue Applications
service line simulation
  arrival rates
    Poisson process
  server model
    serve front and remove, or...
    ...remove and serve front
  statistics accumulation
expression conversion
  Dijkstra algorithm
  "infix" to RPN
  build queue of RPN ops

Priority Queues
"remove" gets highest value
application:
  event queue

Priority Queue Operations
add: add a value
peek: "view" highest value
poll: remove highest value
java.util.Queue interface
java.util.PriorityQueue class
isEmpty, Iterable

Priority Queue Application
service line simulation: events
  end-of-service events
    schedule next event instead of...
    ...polling each queue

 private static class eEvent implements Comparable<Event>
  {
    ...
    private int time;

    ...

    public int compareTo(Event e)
    {
      return (time - e.time);
    }

    ...
  }  
Arrays Of Lists
Queue<String>[] a = new Queue[10];
for (int i = 0; i < a.length; i++)
  a[i] = new LinkedList<String>();

Stack<String>[] b = new Stack[10];
for (int i = 0; i < b.length; i++)
  b[i] = new Stack<String>();

Queue<String>[] c = new Queue[10];
for (int i = 0; i < c.length; i++)
  c[i] = new PriorityQueue<String>();
Cloning A List
for lists "a", this does not make a copy:
b = a; // 2 references to same list
but this does (e.g., for Stacks):
b = (Stack)a.clone();

Hash Maps
Java's hash tables
java.util.Map interface
java.util.HashMap class
application:
  adding variables to expression evaluator


[ Home | Contact Prof. Burns ]