CS226 -- Day 14 -- Spring 2013 (We finished the positionalList complexity worksheet.) STACKS ========================================================== - LIFO: last in, first out - applications: - recursion stack - method stack - operand stack - webbrowser back button - ADT: (interface) public interface Stack { public void push(T o); public T pop() throws StackEmptyException; public T top() throws StackEmptyException; public int size(); public boolean isEmpty(); } - Exception class - we define it to extend API RuntimeException: public class StackEmptyException extends RuntimeException { public StackEmptyException() { super("ERROR: stack is empty, invalid operation"); } public StackEmptyException(String err) { super(err); } } Stack using Array - keep track of top element, add for push, subtract for pop, init to -1 - running time of methods - all are O(1) if top is right side of array - space usage: O(CAP) >= actual # of elements in stack - limited by array size, need to worry about stack full: (or resize) public class StackFullException extends RuntimeException { public StackFullException(String err) { super(err); } } Stack using singly linked list: O(1) time & space for all - push = add head, pop = delete head, top = get head QUEUES ============================================================== - FIFO: first in, first out - applications: - simulate grocery line - job scheduling - ADT: (interface) public interface Queue { public void enqueue(Object o); (add to back) public Object dequeue() throws QueueEmptyException; (remove front) public Object front() throws QueueEmptyException; public int size(); public boolean isEmpty(); } - Exception class would be similar to that for StackEmptyException Queue using linked list: single or circular with tail marker - enqueue = add tail - dequeue = delete head - front = get head - O(1) time & space In singly linked list dequeue is O(N) if you reverse the implementation (add head, delete tail), even with a tail marker because it takes O(N) to move the tail marker backwards when you delete. If you use a doubly linked list, it doesn't matter how you orient the Queue, all operations are O(1). Queue using Array - wrap around indices (circular array) - keep track of front (dequeue) and rear (enqueue) indices - worry about QueueFullException (or resize) - running time of methods - all are O(1) (amortized add with resizing) - space usage: O(CAP) >= actual # of elements - we wrote QueueArray.java! Here X represents an array location that has data. When rear or front get to N-1, then wrap around to 0 again front rear 0 1 2 3 4 5 6 7 8 9 ... N-1 X X X X X rear front 0 1 2 3 4 5 6 7 8 9 ... N-1 --> X X X X X X X -->