Algs4-1.3.36随机迭代器

1.3.36随机迭代器。为上一题中的RandomQueue<Item>编写一个迭代器,随机返回队列中的所有元素。
答:
图片
import java.util.Iterator;
public class RandomQueue<Item> implements Iterable<Item>
{
    private int N=0;
    private Item[] a=(Item[]) new Object[1];
    public RandomQueue()
    {
    }
   
    public boolean isEmpty()
    {return N==0;}
   
    public void enqueue(Item item)
    {
        if(N==a.length) resize(2*N);
        a[N]=item;
        N++;
    }
   
    public Item dequeue()
    {
        int r=StdRandom.uniform(N);
        Item item=a[r];
        a[r]=a[N-1];
        N--;
        if(N==a.length/4) resize(2*N);
        return item;
     }
   
    public Item sample()
    {
        int r=StdRandom.uniform(N);
        return a[r];
    }
   
    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 Iterator<Item> iterator()  {return new ListIterator();}
   
    private class ListIterator implements Iterator<Item>
    {
        private int index=0;
        public ListIterator()
        {
            for (int i = 0; i < N; i++)
            {
               int r = i + StdRandom.uniform(N-i);     // between i and n-1
               Item temp = a[i];
               a[i] = a[r];
               a[r] = temp;
            }
        }
        public boolean hasNext(){return index!=N;}
        public void remove(){}
        public Item next()
        {
           
            Item item=a[index];
            index++;
            return item;
        }//end next
      }//end class ListIterator
    public static void main(String[] args)
    {
        RandomQueue<Card> cards=new RandomQueue<Card>();

       
        for(int value=1;value<=13;value++)
            for(int type=1;type<=4;type++)
               {
                  Card c=new Card();
                  c.value=value;
                  c.type=type;
                  cards.enqueue(c);
              }//end for
     
      while(!cards.isEmpty())
      {
           Card c=cards.dequeue();
           StdOut.print("("+c.value+"," +c.type+")");
      }//end while
   }//end main
}//end class

posted @ 2018-10-26 08:39  修电脑的龙生  阅读(163)  评论(0编辑  收藏  举报