Algs4-1.3.14使用定长数组编写一个类ResizingArrayQueueOfStrings非环形队列

1.3.14编写一个类ResizingArrayQueueOfStrings,使用定长数组实现队列的抽象,然后扩展实现,使用调整数的方法突破大小的限制。
答:
用例数据:
0
1
2
3
4
5
6
7
8
9
入队,出队时的效果:
图片
public class ResizingArrayQueueOfString
{
    private String[] a=new String[1];
    private int N=0;
    private int first;
    private int last;
       
    public boolean isEmpty()
    {return N==0;}
   
    public int size()
    {return N;}
   
    public int first()
    {
        return first;
    }
   
    public int last()
    {
        return last;
    }
   
    public int arrayLength()
    {
        return a.length;
    }
   
    public void enqueue(String item)
    {
        if(N==0)
        {
            resize(1);
            first=0;
            last=0;
            N++;
            a[0]=item;
        }
        else
        {
            if(last==a.length-1) resize(2*a.length);
            last++;
            N++;
            a[last]=item;
        }
    }
   
    public String dequeue()
    {
       if(N>0)
       {
        String item=a[first];
        first++;
        N--;
        if(N==a.length/4) resize(a.length/2);
         return item;
       }
       else
            return null;
   }
   
   private void resize(int max)
   {
       String[] temp=new String[max];
       for(int i=first;i<=last;i++)
           temp[i-first]=a[i];
       a=temp;
       first=0;
       if(N>0)
         last=N-1;
       else
           last=0;
      
   }
    public static void main(String[] args)
    {
      ResizingArrayQueueOfString q=new ResizingArrayQueueOfString ();
        while(!StdIn.isEmpty())
        {
            String item=StdIn.readString();
            q.enqueue(item);
            StdOut.printf("enqueueu item=%s,array length=%d N=%d,first=%d,last=%d\n\n",item,q.arrayLength(),q.size(),q.first(),q.last());
        }//end while
       
        StdOut.println("--------------------");
        while(!q.isEmpty())
        {
            String item=q.dequeue();
            StdOut.printf("dequeueu item=%s,array length=%d N=%d,first=%d,last=%d\n\n",item,q.arrayLength(),q.size(),q.first(),q.last());
        }//end while
      
    }//end main
}//end class

posted @ 2018-10-25 14:03  修电脑的龙生  阅读(269)  评论(0编辑  收藏  举报