package com.qiusongde; import java.util.Iterator; import java.util.NoSuchElementException; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class FixedCapacityStackOfStrings implements Iterable<String> { private String[] a; private int n; public FixedCapacityStackOfStrings(int cap) { a = new String[cap]; n = 0; } public void push(String item) { if(isFull()) throw new IndexOutOfBoundsException("FiexdCapcityStackOfString is Full"); a[n++] = item; } public String pop() { if(isEmpty()) throw new NoSuchElementException("FiexdCapcityStackOfString is empty"); return a[--n]; } //1.3.1 public boolean isFull() { return n == a.length; } public boolean isEmpty() { return n == 0; } public int size() { return n; } @Override public Iterator<String> iterator() { return new ReverseArrayIterator(); } private class ReverseArrayIterator implements Iterator<String> { private int i = n; @Override public boolean hasNext() { return i > 0; } @Override public String next() { return a[--i]; } } public static void main(String[] args) { int max = 5; FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max); StdOut.println("stack initialized max size is:" + max); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) { if(stack.isFull()) StdOut.println("push error, stack full"); else { stack.push(item); StdOut.println("push success:" + item + " size:" + stack.size()); StdOut.print("Left on stack: "); for (String s : stack) { StdOut.print(s + " "); } StdOut.println(); } } else { if(stack.isEmpty()) StdOut.println("pop error, stack empty"); else { StdOut.println("pop success:" + stack.pop() + " size:" + stack.size()); StdOut.print("Left on stack: "); for (String s : stack) { StdOut.print(s + " "); } StdOut.println(); } } } } }
stack initialized max size is:5 to push success:to size:1 Left on stack: to be push success:be size:2 Left on stack: be to or push success:or size:3 Left on stack: or be to not push success:not size:4 Left on stack: not or be to to push success:to size:5 Left on stack: to not or be to be push error, stack full - pop success:to size:4 Left on stack: not or be to - pop success:not size:3 Left on stack: or be to - pop success:or size:2 Left on stack: be to - pop success:be size:1 Left on stack: to - pop success:to size:0 Left on stack: - pop error, stack empty