zoukankan      html  css  js  c++  java
  • 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()+ " ");
       }
    }
  • 相关阅读:
    5、文件处理
    6、Python模块
    4、字典使用
    3、列表 list
    1、Python基础
    2、循环判断
    配置LOG4J(log4j-1.2.17)
    File /WEB-INF/web.xml not found...
    关于TOMCAT的 ROOT/WEB-INF/web.xml的配置
    tomcat 配置系列3
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854350.html
Copyright © 2011-2022 走看看