算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

1.

package algorithms.stacks13;

/******************************************************************************
 *  Compilation:  javac ResizingArrayBag.java
 *  Execution:    java ResizingArrayBag
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  Bag implementation with a resizing array.
 *
 ******************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;

import algorithms.util.StdOut;

/**
 *  The <tt>ResizingArrayBag</tt> class represents a bag (or multiset) of 
 *  generic items. It supports insertion and iterating over the 
 *  items in arbitrary order.
 *  <p>
 *  This implementation uses a resizing array.
 *  See {@link LinkedBag} for a version that uses a singly-linked list.
 *  The <em>add</em> operation takes constant amortized time; the
 *  <em>isEmpty</em>, and <em>size</em> operations
 *  take constant time. Iteration takes time proportional to the number of items.
 *  <p>
 *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class ResizingArrayBag<Item> implements Iterable<Item> {
    private Item[] a;         // array of items
    private int N;            // number of elements on stack

    /**
     * Initializes an empty bag.
     */
    public ResizingArrayBag() {
        a = (Item[]) new Object[2];
        N = 0;
    }

    /**
     * Is this bag empty?
     * @return true if this bag is empty; false otherwise
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * Returns the number of items in this bag.
     * @return the number of items in this bag
     */
    public int size() {
        return N;
    }

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

    /**
     * Adds the item to this bag.
     * @param item the item to add to this bag
     */
    public void add(Item item) {
        if (N == a.length) resize(2*a.length);    // double size of array if necessary
        a[N++] = item;                            // add item
    }


    /**
     * Returns an iterator that iterates over the items in the bag in arbitrary order.
     * @return an iterator that iterates over the items in the bag in arbitrary order
     */
    public Iterator<Item> iterator() {
        return new ArrayIterator();
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ArrayIterator implements Iterator<Item> {
        private int i = 0;
        public boolean hasNext()  { return i < N;                               }
        public void remove()      { throw new UnsupportedOperationException();  }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            return a[i++];
        }
    }

    /**
     * Unit tests the <tt>ResizingArrayBag</tt> data type.
     */
    public static void main(String[] args) {
        ResizingArrayBag<String> bag = new ResizingArrayBag<String>();
        bag.add("Hello");
        bag.add("World");
        bag.add("how");
        bag.add("are");
        bag.add("you");

        for (String s : bag)
            StdOut.println(s);
    }

}

 

2.

  1 package algorithms.stacks13;
  2 
  3 /******************************************************************************
  4  *  Compilation:  javac ResizingArrayQueue.java
  5  *  Execution:    java ResizingArrayQueue < input.txt
  6  *  Dependencies: StdIn.java StdOut.java
  7  *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt  
  8  *  
  9  *  Queue implementation with a resizing array.
 10  *
 11  *  % java ResizingArrayQueue < tobe.txt 
 12  *  to be or not to be (2 left on queue)
 13  *
 14  ******************************************************************************/
 15 
 16 import java.util.Iterator;
 17 import java.util.NoSuchElementException;
 18 
 19 import algorithms.util.StdIn;
 20 import algorithms.util.StdOut;
 21 
 22 /**
 23  *  The <tt>ResizingArrayQueue</tt> class represents a first-in-first-out (FIFO)
 24  *  queue of generic items.
 25  *  It supports the usual <em>enqueue</em> and <em>dequeue</em>
 26  *  operations, along with methods for peeking at the first item,
 27  *  testing if the queue is empty, and iterating through
 28  *  the items in FIFO order.
 29  *  <p>
 30  *  This implementation uses a resizing array, which double the underlying array
 31  *  when it is full and halves the underlying array when it is one-quarter full.
 32  *  The <em>enqueue</em> and <em>dequeue</em> operations take constant amortized time.
 33  *  The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
 34  *  constant time in the worst case. 
 35  *  <p>
 36  *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 37  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 38  *
 39  *  @author Robert Sedgewick
 40  *  @author Kevin Wayne
 41  */
 42 public class ResizingArrayQueue<Item> implements Iterable<Item> {
 43     private Item[] q;       // queue elements
 44     private int N;          // number of elements on queue
 45     private int first;      // index of first element of queue
 46     private int last;       // index of next available slot
 47 
 48 
 49     /**
 50      * Initializes an empty queue.
 51      */
 52     public ResizingArrayQueue() {
 53         q = (Item[]) new Object[2];
 54         N = 0;
 55         first = 0;
 56         last = 0;
 57     }
 58 
 59     /**
 60      * Is this queue empty?
 61      * @return true if this queue is empty; false otherwise
 62      */
 63     public boolean isEmpty() {
 64         return N == 0;
 65     }
 66 
 67     /**
 68      * Returns the number of items in this queue.
 69      * @return the number of items in this queue
 70      */
 71     public int size() {
 72         return N;
 73     }
 74 
 75     // resize the underlying array
 76     private void resize(int max) {
 77         assert max >= N;
 78         Item[] temp = (Item[]) new Object[max];
 79         for (int i = 0; i < N; i++) {
 80             temp[i] = q[(first + i) % q.length];
 81         }
 82         q = temp;
 83         first = 0;
 84         last  = N;
 85     }
 86 
 87     /**
 88      * Adds the item to this queue.
 89      * @param item the item to add
 90      */
 91     public void enqueue(Item item) {
 92         // double size of array if necessary and recopy to front of array
 93         if (N == q.length) resize(2*q.length);   // double size of array if necessary
 94         q[last++] = item;                        // add item
 95         if (last == q.length) last = 0;          // wrap-around
 96         N++;
 97     }
 98 
 99     /**
100      * Removes and returns the item on this queue that was least recently added.
101      * @return the item on this queue that was least recently added
102      * @throws java.util.NoSuchElementException if this queue is empty
103      */
104     public Item dequeue() {
105         if (isEmpty()) throw new NoSuchElementException("Queue underflow");
106         Item item = q[first];
107         q[first] = null;                            // to avoid loitering
108         N--;
109         first++;
110         if (first == q.length) first = 0;           // wrap-around
111         // shrink size of array if necessary
112         if (N > 0 && N == q.length/4) resize(q.length/2); 
113         return item;
114     }
115 
116     /**
117      * Returns the item least recently added to this queue.
118      * @return the item least recently added to this queue
119      * @throws java.util.NoSuchElementException if this queue is empty
120      */
121     public Item peek() {
122         if (isEmpty()) throw new NoSuchElementException("Queue underflow");
123         return q[first];
124     }
125 
126 
127     /**
128      * Returns an iterator that iterates over the items in this queue in FIFO order.
129      * @return an iterator that iterates over the items in this queue in FIFO order
130      */
131     public Iterator<Item> iterator() {
132         return new ArrayIterator();
133     }
134 
135     // an iterator, doesn't implement remove() since it's optional
136     private class ArrayIterator implements Iterator<Item> {
137         private int i = 0;
138         public boolean hasNext()  { return i < N;                               }
139         public void remove()      { throw new UnsupportedOperationException();  }
140 
141         public Item next() {
142             if (!hasNext()) throw new NoSuchElementException();
143             Item item = q[(i + first) % q.length];
144             i++;
145             return item;
146         }
147     }
148 
149    /**
150      * Unit tests the <tt>ResizingArrayQueue</tt> data type.
151      */
152     public static void main(String[] args) {
153         ResizingArrayQueue<String> q = new ResizingArrayQueue<String>();
154         while (!StdIn.isEmpty()) {
155             String item = StdIn.readString();
156             if (!item.equals("-")) q.enqueue(item);
157             else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
158         }
159         StdOut.println("(" + q.size() + " left on queue)");
160     }
161 
162 }

 

3.

  1 package algorithms.stacks13;
  2 
  3 /******************************************************************************
  4  *  Compilation:  javac ResizingArrayStack.java
  5  *  Execution:    java ResizingArrayStack < input.txt
  6  *  Dependencies: StdIn.java StdOut.java
  7  *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
  8  *  
  9  *  Stack implementation with a resizing array.
 10  *
 11  *  % more tobe.txt 
 12  *  to be or not to - be - - that - - - is
 13  *
 14  *  % java ResizingArrayStack < tobe.txt
 15  *  to be not that or be (2 left on stack)
 16  *
 17  ******************************************************************************/
 18 
 19 import java.util.Iterator;
 20 import java.util.NoSuchElementException;
 21 
 22 import algorithms.util.StdIn;
 23 import algorithms.util.StdOut;
 24 
 25 /**
 26  *  The <tt>ResizingArrayStack</tt> class represents a last-in-first-out (LIFO) stack
 27  *  of generic items.
 28  *  It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
 29  *  for peeking at the top item, testing if the stack is empty, and iterating through
 30  *  the items in LIFO order.
 31  *  <p>
 32  *  This implementation uses a resizing array, which double the underlying array
 33  *  when it is full and halves the underlying array when it is one-quarter full.
 34  *  The <em>push</em> and <em>pop</em> operations take constant amortized time.
 35  *  The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
 36  *  constant time in the worst case. 
 37  *  <p>
 38  *  For additional documentation,
 39  *  see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 40  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 41  *
 42  *  @author Robert Sedgewick
 43  *  @author Kevin Wayne
 44  */
 45 public class ResizingArrayStack<Item> implements Iterable<Item> {
 46     private Item[] a;         // array of items
 47     private int N;            // number of elements on stack
 48 
 49 
 50     /**
 51      * Initializes an empty stack.
 52      */
 53     public ResizingArrayStack() {
 54         a = (Item[]) new Object[2];
 55         N = 0;
 56     }
 57 
 58     /**
 59      * Is this stack empty?
 60      * @return true if this stack is empty; false otherwise
 61      */
 62     public boolean isEmpty() {
 63         return N == 0;
 64     }
 65 
 66     /**
 67      * Returns the number of items in the stack.
 68      * @return the number of items in the stack
 69      */
 70     public int size() {
 71         return N;
 72     }
 73 
 74 
 75     // resize the underlying array holding the elements
 76     private void resize(int capacity) {
 77         assert capacity >= N;
 78         Item[] temp = (Item[]) new Object[capacity];
 79         for (int i = 0; i < N; i++) {
 80             temp[i] = a[i];
 81         }
 82         a = temp;
 83     }
 84 
 85     /**
 86      * Adds the item to this stack.
 87      * @param item the item to add
 88      */
 89     public void push(Item item) {
 90         if (N == a.length) resize(2*a.length);    // double size of array if necessary
 91         a[N++] = item;                            // add item
 92     }
 93 
 94     /**
 95      * Removes and returns the item most recently added to this stack.
 96      * @return the item most recently added
 97      * @throws java.util.NoSuchElementException if this stack is empty
 98      */
 99     public Item pop() {
100         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
101         Item item = a[N-1];
102         a[N-1] = null;                              // to avoid loitering
103         N--;
104         // shrink size of array if necessary
105         if (N > 0 && N == a.length/4) resize(a.length/2);
106         return item;
107     }
108 
109 
110     /**
111      * Returns (but does not remove) the item most recently added to this stack.
112      * @return the item most recently added to this stack
113      * @throws java.util.NoSuchElementException if this stack is empty
114      */
115     public Item peek() {
116         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
117         return a[N-1];
118     }
119 
120     /**
121      * Returns an iterator to this stack that iterates through the items in LIFO order.
122      * @return an iterator to this stack that iterates through the items in LIFO order.
123      */
124     public Iterator<Item> iterator() {
125         return new ReverseArrayIterator();
126     }
127 
128     // an iterator, doesn't implement remove() since it's optional
129     private class ReverseArrayIterator implements Iterator<Item> {
130         private int i;
131 
132         public ReverseArrayIterator() {
133             i = N-1;
134         }
135 
136         public boolean hasNext() {
137             return i >= 0;
138         }
139 
140         public void remove() {
141             throw new UnsupportedOperationException();
142         }
143 
144         public Item next() {
145             if (!hasNext()) throw new NoSuchElementException();
146             return a[i--];
147         }
148     }
149 
150 
151     /**
152      * Unit tests the <tt>Stack</tt> data type.
153      */
154     public static void main(String[] args) {
155         ResizingArrayStack<String> s = new ResizingArrayStack<String>();
156         while (!StdIn.isEmpty()) {
157             String item = StdIn.readString();
158             if (!item.equals("-")) s.push(item);
159             else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
160         }
161         StdOut.println("(" + s.size() + " left on stack)");
162     }
163 }

 

posted @ 2016-04-21 11:44  shamgod  阅读(354)  评论(0编辑  收藏  举报
haha