zoukankan      html  css  js  c++  java
  • 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();
        }
    }
       
  • 相关阅读:
    Windows Server 2003 服务器备份和恢复技巧
    查询表一张表的列名及字段类型
    aix 维护常用命令
    从 p12 格式 SSL 证书解出 pem 格式公钥私钥给 Postman 使用
    微信添加好友、加群的限制
    python requests 设置 proxy 和 SSL 证书
    blog post template(步骤类)
    post template(调查类)
    clip at cnblogs log
    《什么才是公司最好的福利》读后感
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854319.html
Copyright © 2011-2022 走看看