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("\nQueue left elements is:\n");
        gq.showAll();
    }
}
   
posted @ 2018-10-26 08:40  修电脑的龙生  阅读(181)  评论(0编辑  收藏  举报