用数组结构实现固定大小的队列

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-16 23:40   39   0
public class QueByArrary {
 private Integer[] arr;
 private Integer size;
 private Integer first;
 private Integer last;
 
 public QueByArrary(int initSize){
  if(initSize<=0){
   throw new IllegalArgumentException("The init size is less than 0");
  }
  arr=new Integer[initSize];
  size=0;
  first=0;
  last=0;
 }
 
 public void push(Integer num){
  if(size==arr.length){
   throw new ArrayIndexOutOfBoundsException("The que is full");
  }
  size++;
  last=(last==arr.length?0:last);
  arr[last++]=num;
 }
 /**
  * 弹出队列第一个位置的数,不移除
  * @return
  */
 public Integer peek(){
  if(size==0){
   throw new ArrayIndexOutOfBoundsException("The queue is empty");
  }
  return arr[first];
 }
 
 /**
  * 弹出队列第一个位置的数并移除
  * @return
  */
 public Integer pop(){
  if(size==0){
   throw new ArrayIndexOutOfBoundsException("The queue is empty");
  }
  size--;
  int temp=first;
  first=(first==arr.length-1?0:first+1);
  return arr[temp];
 }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP