Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Data Structures revisited Stack: What problems does it solve?

 Linked lists and arrays and ArrayLists and …  Stacks are used to avoid recursion, a stack can replace the
 Linear structures, operations include insert, delete,
implicit/actual stack of functions called recursively
traverse, …  Stacks are used to evaluate arithmetic expressions, to
 Advantages and trade-offs include … implement compilers, to implement interpreters
 The Java Virtual Machine (JVM) is a stack-based
machine
 We want to move toward structures that support very
 Postscript is a stack-based language
efficient insertion and lookup, lists can't do better than O(n)
for one of these: consider binary search and insert for arrays,  Stacks are used to evaluate arithmetic expressions in

or insert and lookup for linked lists many languages

 Small set of operations: LIFO or last in is first out access


 Interlude: two linear structures that facilitate certain
 Operations: push, pop, top, create, clear, size
algorithms: Stack and Queue
 More in postscript, e.g., swap, dup, rotate, …
 Restricted access linear structures

CPS 100 5.1 CPS 100 5.2

Simple stack example Implementation is very simple


 Stack is part of java.util.Collections hierarchy  Extends Vector, so simply wraps Vector/ArrayList methods
 It's an OO abomination, extends Vector (like ArrayList)
in better names
 push==add, pop==remove (also peek and empty)
• Should be implemented using Vector
 Note: code below for ArrayList, Vector is used
• Doesn't model "is-a" inheritance
• Stack is generic, so Object replaced by generic reference
 what does pop do? What does push do? (see next slide)
Stack<String> s = new Stack<String>();
public Object push(Object o){
s.push("panda");
s.push("grizzly"); add(o);
s.push("brown"); return o;
System.out.println("size = "+s.size()); }
System.out.println(s.peek()); public Object pop(){
String str = s.pop(); return remove(size()-1);
System.out.println(s.peek()); }
System.out.println(s.pop());

CPS 100 5.3 CPS 100 5.4


Implementation is very simple Uses rather than "is-a"
 Extends Vector, so simply wraps Vector/ArrayList methods  Suppose there's a private ArrayList myStorage
in better names  Doesn't extend Vector, simply uses Vector/ArrayList
 What does generic look like?  Disadvantages of this approach?
• Synchronization issues
public class Stack<E> extends ArrayList<E> {
public E push(E o){ public class Stack<E> {
private ArrayList<E> myStorage;
add(o);
public E push(E o){
return o; myStorage.add(o);
} return o;
public E pop(Object o){ }
return remove(size()-1); public E pop(o){
} return myStorage.remove(size()-1);
}

CPS 100 5.5 CPS 100 5.6

Postfix, prefix, and infix notation Exceptions


 Postfix notation used in some HP calculators  Exceptions are raised or thrown in exceptional cases
 No parentheses needed, precedence rules still respected  Bad indexes, null pointers, illegal arguments, …
3 5 + 4 2 * 7 + 3 - 9 7 + *  File not found, URL malformed, …
 Read expression
• For number/operand: push  Runtime exceptions aren't meant to be handled or caught
• For operator: pop, pop, operate, push  Bad index in array, don't try to handle this in code
 Null pointer stops your program, don't code that way!
 See Postfix.java for example code, key ideas:
 Use StringTokenizer, handy tool for parsing
 Other exceptions must be caught or rethrown
 Note: Exceptions thrown, what are these?
 See FileNotFoundException and IOException in
 What about prefix and infix notations, advantages? Scanner class implementation
 RuntimeException extends Exception, catch not required

CPS 100 5.7 CPS 100 5.8


Prefix notation in action Postfix notation in action
 Scheme/LISP and other functional languages tend to use a  Practical example of use of stack abstraction
prefix notation  Put operator after operands in expression
 Use stack to evaluate
(define (square x) (* x x)) • operand: push onto stack
• operator: pop operands push result
(define (expt b n)  PostScript is a stack language mostly used for printing
(if (= n 0)  drawing an X with two equivalent sets of code
1 %!
%!
(* b (expt b (- n 1))))) 200 200 moveto
100 100 rlineto 100 –100 200 300 100 100 200 200
200 300 moveto moveto rlineto moveto rlineto
100 –100 rlineto stroke showpage
stroke showpage

CPS 100 5.9 CPS 100 5.10

Queue: another linear ADT Stack and Queue implementations


 FIFO: first in, first out, used in many applications  Different implementations of queue (and stack) aren’t really
 Scheduling jobs/processes on a computer
interesting from an algorithmic standpoint
 Complexity is the same, performance may change (why?)
 Tenting policy?
 Use ArrayList, growable array, Vector, linked list, …
 Computer simulations
• Any sequential structure

 Common operations: add (back), remove (front), peek ??  As we'll see java.util.LinkedList is good basis for all
 java.util.Queue is an interface (jdk5)  In Java 5, LinkedList implements the Queue interface,
• offer(E), remove(), peek(), size() low-level linked lists facilitate (circular list!)
 java.util.LinkedList implements the interface
• add(), addLast(), getFirst(), removeFirst()  ArrayList for queue is tricky, ring buffer implementation,
add but wrap-around if possible before growing
 Downside of using LinkedList as queue
 Tricky to get right (exercise left to reader)
 Can access middle elements, remove last, etc. why?

CPS 100 5.11 CPS 100 5.12


Using linear data structures Maria Klawe
 We’ve studied arrays, stacks, queues, which to use? Chair of Computer Science at
UBC, Dean of Engineering at
 It depends on the application Princeton, President of Harvey
 ArrayList is multipurpose, why not always use it? Mudd College, ACM Fellow,…
• Make it clear to programmer what’s being done
Klawe's personal interests include
• Other reasons? painting, long distance running,
hiking, kayaking, juggling and
playing electric guitar. She
 Other linear ADTs exist describes herself as "crazy about
 List: add-to-front, add-to-back, insert anywhere, iterate mathematics" and enjoys playing
video games.
• Alternative: create, head, tail, Lisp or
• Linked-list nodes are concrete implementation
"I personally believe that the most
 Deque: add-to-front, add-to-back, random access important thing we have to do today
• Why is this “better” than an ArrayList? is use technology to address societal
• How to implement? problems, especially in developing
regions"

CPS 100 5.13 CPS 100 5.14

Queue applications Blob Finding with Queues


 Simulation, discrete-event simulation myGrid[row][col] = fillWith; // mark pixel
 How many toll-booths do we need? How many express
size++; // count pixel
myQueue.add(myPairGrid[row][col]);
lanes or self-checkout at grocery store? Runway access at
while (myQueue.size() != 0){
aiport? Pair p = myQueue.remove();
 Queues facilitate simulation with mathematical for(int k=0; k < rowDelta.length; k++){
distributions governing events, e.g., Poisson distribution row = p.row + rowDelta[k];
for arrival times col = p.col + colDelta[k];
if (inRange(row,col) &&
myGrid[row][col] == lookFor){
 Shortest path, e.g., in flood-fill to find path to some myQueue.add(myPairGrid[row][col]);
neighbor or in word-ladder myGrid[row][col] = fillWith;
 How do we get from "white" to "house" one-letter at a size++;
time? }
}
• white, while, whale, shale, shake, …? }

CPS 100 5.15 CPS 100 5.16


Queue for shortest path (see APT) Shortest Path reprised
public boolean ladderExists(String[] words,  How does use of Queue ensure we find shortest path?
String from, String to){
Queue<String> q = new LinkedList<String>();  Where are words one away from start?
Set<String> used = new TreeSet<String>();  Where are words two away from start?
for(String s : words){
if (oneAway(from,s)){
q.add(s);  Why do we need to avoid revisiting a word, when?
used.add(s);
 Why do we use a set for this? Why a TreeSet?
}
}  Alternatives?
while (q.size() != 0){
String current = q.remove();
if (oneAway(current,to)) return true;  What if we want the ladder, not just whether it exists
// add code here, what?
 What’s path from white to house? We know there is one.
}
return false;  Ideas? Options?
}

CPS 100 5.17 CPS 100 5.18

You might also like