import edu.princeton.cs.algs4.*; publicclassq133{ publicstaticvoidmain(String[] args){ StdOut.println("请输入判断的数据:"); int[] num = newint[10]; //选项数组 for (int i = 0; i < 10; i++){ num[i] = StdIn.readInt(); } Stack<Integer> detection = new Stack<Integer>(); //检测栈 int[] ans = newint[10]; //结果数组 for (int i = 0, n = 0, a = 0; i < 10; i++){ if (i != num[n]){ detection.push(i); } else { int c = 0; do { ans[a] = num[n]; a++; n++; if (!detection.isEmpty()){ c = detection.pop(); detection.push(c); } } while (!detection.isEmpty() && detection.pop() == num[n]); if (!detection.isEmpty()){ detection.push(c); } } } int s = 0; for (int p = 0; p < 10; p++ ){ if (ans[p] != num[p]){ s = 1; StdOut.print("false"); break; } } if (s == 0){ StdOut.print("true"); }
publicDoublingStackOfStrings(){ a = new String[2]; N = 0; }
// is the stack empty? publicbooleanisEmpty(){ return (N == 0); }
// resize the underlying array holding the elements privatevoidresize(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 publicvoidpush(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()) { thrownew 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; }
public Iterator<String> iterator(){ returnnew ReverseArrayIterator(); }
publicintsize(){ return N; }
// an iterator, doesn't implement remove() since it's optional privateclassReverseArrayIteratorimplementsIterator<String> { privateint i = N; publicbooleanhasNext(){ return i > 0; } publicvoidremove(){ thrownew UnsupportedOperationException(); }
public String next(){ if (!hasNext()) thrownew NoSuchElementException(); return a[--i]; }
}
// test client publicstaticvoidmain(String[] args){ DoublingStackOfStrings s = new DoublingStackOfStrings(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) { s.push(item); } elseif (s.isEmpty()) { StdOut.println("BAD INPUT"); } else { s.pop(); } } StdOut.println(s.size());
while (!s.isEmpty()){ StdOut.println(s.pop()); } }