001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package algs13;
import stdlib.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
/* ***********************************************************************
 *  Compilation:  javac ResizingArrayStack.java
 *  Execution:    java ResizingArrayStack < input.txt
 *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
 *
 *  Stack implementation with a resizing array.
 *
 *  % more tobe.txt
 *  to be or not to - be - - that - - - is
 *
 *  % java ResizingArrayStack < tobe.txt
 *  to be not that or be (2 left on stack)
 *
 *************************************************************************/
public class ResizingArrayStack<T> implements Iterable<T> {
  private T[] a;        // array of items
  private int N;        // number of elements on stack

  // create an empty stack
  @SuppressWarnings("unchecked")
  public ResizingArrayStack() {
    this.a = (T[]) new Object[2];
    this.N = 0;
  }

  public boolean isEmpty() { return N == 0; }
  public int size()        { return N;      }


  // resize the underlying array holding the elements
  @SuppressWarnings("unchecked")
  private void resize(int capacity) {
    if (capacity <= N) throw new IllegalArgumentException ();
    T[] temp = (T[]) new Object[capacity];
    for (int i = 0; i < N; i++)
      temp[i] = a[i];
    a = temp;
  }

  // push a new item onto the stack
  public void push(T item) {
    if (N == a.length) resize(2*N); // increase array size if necessary
    //if (N == a.length) resize((int)Math.ceil (N*1.5));
    a[N] = item;
    N++;
  }

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

  /**
   * Return string representation.
   */
  public String toString() {
    StringBuilder s = new StringBuilder();
    for (T item : this)
      s.append(item + " ");
    return s.toString();
  }
  
  public Iterator<T> iterator()  { return new ReverseArrayIterator();  }

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

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

  /* *********************************************************************
   * Test routine.
   **********************************************************************/
//  public static void bookMain(String[] args) {
//    StdIn.fromString ("to be or not to - be - - that - - - is");
//
//    ResizingArrayStack<String> s = new ResizingArrayStack<>();
//    while (!StdIn.isEmpty()) {
//      String item = StdIn.readString();
//      if (!item.equals("-")) s.push(item);
//      else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
//    }
//    StdOut.println("(" + s.size() + " left on stack)");
//  }
//
  /* *********************************************************************
   * Test routine.
   **********************************************************************/
  public static void main(String[] args) {
    double prevTime = 1;
    for (int i = 0, size = 20; i<19; i += 1, size *= 2) {
      Stopwatch s = new Stopwatch ();

      for (int k = 0; k < 1; k++) {
        ResizingArrayStack<Double> stack = new ResizingArrayStack<> ();
        for (int j = 0; j < size; j++) {
          stack.push (1.2);
        }
      }

      double thisTime = s.elapsedTime ();
      StdOut.format ("size=%d thisTime=%f ratio=%f\n", size, thisTime, thisTime/prevTime);
      prevTime = thisTime;
    }
  }
  public static void main2 (String[] args) {
    //Trace.showObjectIdsRedundantly (true);
    Trace.showBuiltInObjects (true);
    //Trace.showBuiltInObjectsVerbose (true);
    Trace.drawStepsOfMethod ("main");
    Trace.drawStepsOfMethod ("resize");
    Trace.run ();
    
    ResizingArrayStack<Integer> s1 = new ResizingArrayStack<> ();
    ResizingArrayStack<String> s2 = new ResizingArrayStack<> ();
    s1.push (11);
    s1.push (21);
    s1.push (31);

    //s2.push (41);
    s2.push ("duck");
    s2.push ("goose");
  }
}