• Algs4-1.4.30一个栈和一个steque实现的双向队列


    1.4.30一个栈和一个steque实现的双向队列。使用一个栈和steque实现一个双向队列(请见练习1.3.32),使得双向队列的每个操作所需的栈和steque操作均摊后为一个常数。
    答:
    图片
    public class E1d4d30<Item>
    {
        Stack<Item> s=new Stack<Item>();
        Steque<Item> ste=new Steque<Item>();
        public boolean isEmpty()
        {
            return s.isEmpty() && ste.isEmpty();
        }
       
        public int size()
        {
            return s.size()+ste.size();
        }
       
        public void pushLeft(Item item)
        {
            ste.push(item);
        }
       
        public Item popLeft()
        {
           
     if(s.isEmpty())
              while(!ste.isEmpty())
                  s.push(ste.pop());
            //
            Item item=s.pop();
            return item;
        }
       
        public void pushRight(Item item)
        {
            ste.push(item);
        }
       
        public Item popRight()
        {
            if(ste.isEmpty())
                while(!s.isEmpty())
                   ste.push(s.pop());
           return  ste.pop();
        }
       
       
        public static void main(String[] args)
        {
            E1d4d30<String> d=new E1d4d30<String>();
            StdOut.printf("Deque is empty:%s ",d.isEmpty());
            d.pushLeft("1");
            StdOut.printf("Deque size is:%d ",d.size());
            d.pushRight("2");
            StdOut.printf("Deque size is:%d ",d.size());
            StdOut.printf("popLeft is:%s ",d.popLeft());
            StdOut.printf("popLeft is:%s ",d.popLeft());
            //
            d.pushLeft("1");
            d.pushRight("2");
            d.pushRight("3");
            StdOut.printf("popLeft is %s ",d.popLeft());
            StdOut.printf("popRight is %s ",d.popRight());
        }
     }


  • 相关阅读:
    8.20Java之反射机制的基本概念
    8.18Go语言之字符串
    Debug
    Feign
    Nacos
    SpringCloud Alibaba
    SpringCloud
    Maven
    Maven
    Jenkins
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854496.html
Copyright © 2020-2023  润新知