DoublingStackOfStrings.java


Below is the syntax highlighted version of DoublingStackOfStrings.java from §4.3 Stacks and Queues.


/*************************************************************************
 *  Compilation:  javac DoublingStackOfStrings.java
 *  Execution:    java DoublingStackOfStrings
 *  
 *  Stack of strings implementation with an array.
 *  Resizes by doubling and halving.
 *
 *************************************************************************/

public class DoublingStackOfStrings {
    private String[] a;
    private int N;

    public DoublingStackOfStrings() {
        a = new String[2];
        N = 0;
    }

    // is the stack empty?
    public boolean isEmpty() {  return (N == 0);  }

    // resize the underlying array holding the elements
    private void resize(int capacity) {
        String[] temp = new String[capacity];
        for (int i = 0; i < N; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    // push a new item onto the stack
    public void push(String item) {
        if (N == a.length) resize(2*a.length);
        a[N++] = item;
    }

    // delete and return the item most recently added
    public String pop() {
        if (isEmpty()) { throw new RuntimeException("Stack underflow error"); }
        String item = a[--N];
        a[N] = null;  // to avoid loitering
        if (N > 0 && N == a.length/4) resize(a.length/2);
        return item;
    }


    // test client
    public static void main(String[] args) {
        DoublingStackOfStrings s = new DoublingStackOfStrings();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) s.push(item);
            else if (s.isEmpty())  StdOut.println("BAD INPUT");
            else                   StdOut.print(s.pop());
        }
    }

}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.