数组实现队列

public static class ArrayQueue{
       private int [] arr;
       private int pushIndex; //入队index
       private int popIndex; //出队index
       private int size;//当前队列的size
       private final int limit;//数组的固定大小

       public ArrayQueue(int limit) {
           arr = new int[limit];
           pushIndex = 0;
           popIndex = 0;
           size = 0;
           this.limit = limit;
       }
       public void push(int value){
           if(size == limit)
               throw new RuntimeException("栈满");
           size++;
           arr[pushIndex] = value;
           pushIndex = nextIndex(pushIndex);
       }
       public int pop(){
           if(size == 0)
               throw new RuntimeException("栈空");
           size--;
           int res = arr[popIndex];
           popIndex = nextIndex(popIndex);
           return res;
       }
       private int nextIndex(int index){
           return index < limit - 1 ? index + 1 : 0;
       }
   }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容