• Algs4-1.3.38删除第k个元素-数组实现


    1.3.38删除第k个元素。实现一个类并支持表1.3.12中的API:
    表1.3.12泛型一般队列的API
    public class GeneralizedQueue<Item>
        GeneralizedQueue()//创建一条空队列
        boolean isEmpty()//队列是否为空
        void insert(Item x)//添加一个元素
        Item delete(int k)//删除并返回最早插入的第k个元素
    首先用数组实现该数据类型,然后用链表实现该数据类型。注意:我们在第3章中介绍的算法和数据结构可以保证insert()和delete()的实现所需的运行时间和和队列中的元素数量成对数关系-请参见练习3.5.27。
    答:
    图片
    public class GeneralizedQueue<Item>
    {
        private Item[] a=(Item[]) new Object[1];
        private int N=0;
       
        public GeneralizedQueue()
        {}
       
        public boolean isEmpty()
        {return N==0;}
       
       
        public void insert(Item x)
        {
            if(N==a.length) resize(2*N);
            a[N]=x;
            N++;
        }
       
        public Item delete(int k)
        {
            Item item=a[k-1];
            for(int i=k;i<N;i++)
               a[i-1]=a[i];
            N--;
            return item;
        }
       
        private void resize(int max)
        {
            Item[] temp=(Item[]) new Object[max];
            for(int i=0;i<N;i++)
                temp[i]=a[i];
            a=temp;
        }
       
        public  void showAll()
        {
            for(int i=0;i<N;i++)
                StdOut.print(a[i]+ " ");
        }
       
        public static void  main(String[] args)
        {
            int N=Integer.parseInt(args[0]);
            int k=Integer.parseInt(args[1]);
            GeneralizedQueue<Integer> gq=new GeneralizedQueue<Integer>();
            for(int i=0;i<N;i++)
                gq.insert(i);
            //
            StdOut.print("the k is "+k +" the value is "  +gq.delete(k));
            StdOut.printf(" Queue left elements is: ");
            gq.showAll();
        }
    }
       
  • 相关阅读:
    Python sendemail txt,html,图片及附件
    python 3 requests库2个问题
    py37 unitest+html_sendmail
    python 3 unitest批量执行用例
    phthon 3 unittest模块使用
    python 之发送邮件
    ipad已停用 连接itunes怎么办
    Ubuntu 16.04系统挂载4T硬盘
    华硕RT-AC86U路由器 AP模式实现多路由器组网,扩展主路由器的无线网范围
    ubuntu 常用命令
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854319.html
Copyright © 2020-2023  润新知