数组实现队列

2023-10-18  本文已影响0人  ChadJ

思路分析

  1. 创建一个指定容量maxSize的数组,用于存放队列元素;
  2. 声明frontrear,front指向队列头的前一个位置,rear指向队列的当前尾部位置;
  3. 当添加数据时rear向后rear = (rear + 1) % maxSize,如果(rear + 1) % maxSize == front则说明队列满了;
  4. 取出数据时front向后front = (front + 1) % maxSize,如果front == rear则说明队列空了;

代码实现

public class ArrayQueue {
  // 最大容量
  private final int maxSize;
  // 队列前端,指向队列头部的前一个位置
  private int front;
  // 队列尾端,指向队列尾部的当前位置
  private int rear;
  // 用于存储元素
  private int[] arr;

  public ArrayQueue(int maxSize) {
    this.maxSize = maxSize;
    rear = -1;
    front = -1;
    arr = new int[maxSize];
  }

  // 队列是否已满
  private boolean isFull() {
    return (rear + 1) % maxSize == front;
  }

  // 队列是否已空
  private boolean isEmpty() {
    return front == rear;
  }

  public void add(int v) throws Exception {
    if(isFull()) {
      throw new Exception("队列已满");
    }
    this.rear = (this.rear + 1) % maxSize;
    arr[this.rear] = v;
  }
  
  public int get() throws Exception {
    if(isEmpty()) {
      throw new Exception("队列已空");
    }
    this.front = (this.front + 1) % maxSize;

    return arr[this.front];
  }
    
}
上一篇下一篇

猜你喜欢

热点阅读