001package algs13;
002import stdlib.*;
003public class XFixedCapacityStackOfStrings {
004        private String[] a; // holds the items
005        private int N;      // number of items in stack
006        // Invariant (after the constructor):
007        //   a[0]..a[N-1] are non null
008        //   a[N]..a[a.length-1] are null
009        public XFixedCapacityStackOfStrings (int capacity) {
010                this.a = new String[capacity];
011                this.N = 0;
012        }
013        public int size ()        { return N; }
014        public boolean isEmpty () { return (N == 0); }
015        public void push (String item) {
016                if (item == null) throw new IllegalArgumentException ();
017                if (N >= a.length) throw new RuntimeException ("Stack full");
018                a[N] = item;
019                N++;
020        }
021        public String pop () {
022                if (N <= 0) throw new RuntimeException ("Stack empty");
023                N--;
024                String result = a[N];
025                a[N] = null;
026                return result;
027        }
028
029        public static void main(String[] args) {
030                //Trace.showObjectIdsRedundantly (true);
031                //Trace.showBuiltInObjectsVerbose (true);
032                //Trace.drawStepsOfMethod ("main");
033                Trace.drawSteps ();
034                Trace.run ();
035                XFixedCapacityStackOfStrings stack1 = new XFixedCapacityStackOfStrings (7);
036                XFixedCapacityStackOfStrings stack2 = new XFixedCapacityStackOfStrings (3);
037                stack1.push ("a");
038                stack2.push ("b");
039                stack1.push ("c");
040                stack2.push ("d");
041                stack1.push ("e");
042                stack2.push ("f");
043                stack1.push ("g");
044                while (!stack2.isEmpty()) {
045                        StdOut.println (stack2.pop ());
046                }
047                StdOut.println();
048                while (!stack1.isEmpty()) {
049                        StdOut.println (stack1.pop ());
050                }
051        }
052}