数组模拟队列

Posted on 2023-02-23 15:23  。破  阅读(22)  评论(0)    收藏  举报

//使用数组模拟队列-编写一个ArrayQueue类

 class ArrayQueue{
    private int maxSize: //表示数组的最大容量
    private int front; //队列头
    private int rear; //队列尾
    private int [] arr; //该数组用于存放数据,模拟队列


    //创建队列的构造器
    public ArrayQueue( int arrMaxSize){
            maxSize = arrMaxSize;
            arr =  new int [maxSize];
       front = - 1 ; //指向队列头部,分析出front是指向队列头的前一个位置。
       rear = -1;//指向队列尾,指向队列尾的数据
}
  //判断数据是否为满
  public boolean isFull(){
    reutrn rear == maxSize - 1;
  }
}
//判断队列是否为空
public boolean isEmpty(){
    return rear == front;
}
//添加数据到队列
public void addQueue(int n){
//判断队列是否满
if(isFull()){
  System.out.println("队列满,不能加入数据");
  return;
}
rear++;//让rear后移
arr[rear] = n;
}

//获取队列的数据,出队列
  public int getQueue(){
  //判断队列是否空
  if(isEmpty()){
    throw new RuntimeException("队列空,不能取数据");
  }
  front++;//front后移
  return arr[front];  
}
//显示队列的所有数据
public void showQueue(){
//遍历
if(isEmpty()){
  System.out.println("队列空的,没有数据");
  return;
}
  for(int i = 0;i < arr.length;i++){

  

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3