1.3 Bags, Queues, and Stacks.md

来源:互联网 发布:社区app软件 编辑:程序博客网 时间:2024/06/06 01:34

FixedCapacityStackOfStrings

package algorithms;public class FixedCapacityStackOfStrings {    private String[] a;    private int N;    public FixedCapacityStackOfStrings(int cap) {        a = new String[cap];    }    public boolean isEmpty() {        return N == 0;    }    public int size() {        return N;    }    public void push(String item) {        a[N++] = item;    }    public String pop() {        return a[--N];    }}

Test

package algorithms;import edu.princeton.cs.algs4.StdIn;import edu.princeton.cs.algs4.StdOut;public class Test {    public static void main(String[] args) {        FixedCapacityStackOfStrings s = new FixedCapacityStackOfStrings(100);        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 the stack.");    }}

tobe.txt

to be or not to - be - - that - - - is

Output:

 to be not that or be 
0 0