栈与队列

Stack & Queue

No need to give a detailed introduction on these two famous data structures. We will focus on how to implement them in two different approaches - linked lists or resizing arrays.

  • Approach 1. linked lists. (ez)
  • Approach 2. resizing arrays.

Resizing-Array Implementation

Consider an array-based stack. The implementation is trivial; however, we need to know the size NN of the input data to avoid stack overflow.

Therefore, we introduce the resizing arrays to this problem: the resizing arrays grow and shrink dynamically according to the current data size.

  • How to grow array? (operation push()) If array is full, create a new array of twice (repeated doubling) the size, and copy items.
  • How to shrink array? (operation pop()) If array is one-quarter full, create a new array of half the size, and copy items.

Note that we shrink array when it is 1/41/4 full instead of 1/21/2 full to avoid the worst case: push-pop-push-pop...sequence when array is full.

It is proven that the amortized running time of a single push/pop is constant. (in particular, 33)

Note that the array size grow exponentially:  for t-th growth

Linked Lists Versus Resizing Arrays

implementation/cost time space
Linked Lists Every operation takes constant time in the worst case. Use extra space to deal with the links.
Resizing Arrays Every operation takes constant amortized time. Less wasted space.

Code Implementation

Here is a resizing-array implementation for a queue.

java
public class ResizingArrayQueue<Item> implements Iterable<Item> {
    // initial capacity of underlying resizing array
    private static final int INIT_CAPACITY = 8;

    private Item[] q;       // queue elements
    private int n;          // number of elements on queue
    private int first;      // index of first element of queue
    private int last;       // index of next available slot

    // Initializes an empty queue.
    public ResizingArrayQueue() {
        q = (Item[]) new Object[INIT_CAPACITY];
        n = 0;
        first = 0;
        last = 0;
    }

    // return true if this queue is empty; false otherwise
    public boolean isEmpty() {
        return n == 0;
    }

    // Returns the number of items in this queue.
    public int size() {
        return n;
    }

    // resize the underlying array
    private void resize(int capacity) {
        assert capacity >= n;
        Item[] copy = (Item[]) new Object[capacity];
        for (int i = 0; i < n; i++) {
            copy[i] = q[(first + i) % q.length];
        }
        q = copy;
        first = 0;
        last  = n;
    }

    // Adds the item to this queue.
    public void enqueue(Item item) {
        // double size of array if necessary and recopy to front of array
        if (n == q.length) resize(2*q.length);   // double size of array if necessary
        q[last++] = item;                        // add item
        if (last == q.length) last = 0;          // wrap-around
        n++;
    }


    // Removes and returns the item on this queue that was least recently added.
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = q[first];
        q[first] = null;                            // to avoid loitering
        n--;
        first++;
        if (first == q.length) first = 0;           // wrap-around
        // shrink size of array if necessary
        if (n > 0 && n == q.length/4) resize(q.length/2);
        return item;
    }

    // Returns the item least recently added to this queue.
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        return q[first];
    }


    public Iterator<Item> iterator() {
        return new ArrayIterator();
    }

    // an array iterator, from first to last-1
    private class ArrayIterator implements Iterator<Item> {
        private int i = 0;

        public boolean hasNext() {
            return i < n;
        }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = q[(i + first) % q.length];
            i++;
            return item;
        }
    }

    public static void main(String[] args) {
        ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) queue.enqueue(item);
            else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " ");
        }
        StdOut.println("(" + queue.size() + " left on queue)");
    }

}
CC BY-NC-SA 4.0
正在加载评论…