Algs4-1.3.4X栈与队列-两个栈实现一个队列均摊O(1)

图片
 public class QueueWithTwoStack<Item>
{
    Stack<Item> s1=new Stack<Item>();
    Stack<Item> s2=new Stack<Item>();
   
    public boolean isEmpty()
    {
        return s1.isEmpty() && s2.isEmpty();
    }
   
    public int size()
    {
        return s1.size()+s2.size();
    }
   
    public void enqueue(Item item)
    {
        s1.push(item);
    }
   
    public Item dequeue()
    {
        if(s2.isEmpty())
        {
            while(!s1.isEmpty())
              s2.push(s1.pop());
        }
        //
        return s2.pop();
    }
   
   public static void main(String[] args)
   {
       QueueWithTwoStack<String> q=new QueueWithTwoStack<String>();
       q.enqueue("1");
       q.enqueue("2");
       q.enqueue("3");
       //
       StdOut.print(q.dequeue()+ " ");
       //
       q.enqueue("4");
       StdOut.print(q.dequeue()+ " ");
       //
       q.enqueue("5");
       q.enqueue("6");
       //
       while(!q.isEmpty())
          StdOut.print(q.dequeue()+ " ");
   }
}
posted @ 2018-10-26 08:49  修电脑的龙生  阅读(194)  评论(0编辑  收藏  举报