Algs4-1.3链表实现不定容泛型Stack不支持迭代

 public class Stack<Item>
{
    private int N;
    private Node first;
    private class Node
    {
        Item item;
        Node next;
    }
    public boolean isEmpty()
    {return N==0;}
   
    public int size()
    {return N;}
   
    public void push(Item item)
    {
        Node oldfirst=first;
        first=new Node();
        first.item=item;
        first.next=oldfirst;
        N++;
    }
   
    public Item pop()
    {
        Item item=first.item;
        first=first.next;
        N--;
        return item;
    }
   
    public static void main(String[] args)
    {
        Stack<String> s=new Stack<String>();
        while(!StdIn.isEmpty())
        {
            String item=StdIn.readString();
            if(!item.equals("-"))
                s.push(item);
            else if(!s.isEmpty())
                StdOut.print(s.pop()+" ");
        }//end while
        StdOut.println("(" +s.size()+" left on stack)");
    }
}
posted @ 2018-10-25 13:37  修电脑的龙生  阅读(111)  评论(0编辑  收藏  举报