zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Es spring data jpa 修改连接配置
    object转map类型
    记一次项目中yaml文档引发的惨案 (#yaml文档格式#yaml中'-'的作用)
    02-方法重载
    01-数据类型分类
    Centos 7 Sublime 安装 package control
    修改AdminLTE左侧菜单展开延迟
    【Flask】Flask Restful api
    【Flask】Flask常用信号
    【Flask】Flask上下文
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854316.html
Copyright © 2011-2022 走看看