鱼C论坛

 找回密码
 立即注册
查看: 1219|回复: 2

[已解决]循环队列

[复制链接]
发表于 2023-11-13 17:39:52 | 显示全部楼层    本楼为最佳答案   
  1. public class CircularQueue<T> {
  2.     private int front;
  3.     private int rear;
  4.     private int size;
  5.     private T[] elements;

  6.     public CircularQueue(int capacity) {
  7.         elements = (T[]) new Object[capacity];
  8.         front = 0;
  9.         rear = 0;
  10.         size = 0;
  11.     }

  12.     public void enqueue(T element) {
  13.         if (size == elements.length) {
  14.             throw new IllegalStateException("Queue is full");
  15.         }
  16.         elements[rear] = element;
  17.         rear = (rear + 1) % elements.length;
  18.         size++;
  19.     }

  20.     public T dequeue() {
  21.         if (size == 0) {
  22.             throw new NoSuchElementException("Queue is empty");
  23.         }
  24.         T element = elements[front];
  25.         elements[front] = null;
  26.         front = (front + 1) % elements.length;
  27.         size--;
  28.         return element;
  29.     }

  30.     public T getFront() {
  31.         if (size == 0) {
  32.             throw new NoSuchElementException("Queue is empty");
  33.         }
  34.         return elements[front];
  35.     }

  36.     public boolean isEmpty() {
  37.         return size == 0;
  38.     }

  39.     public int size() {
  40.         return size;
  41.     }
  42. }

  43. public class Main {
  44.     public static void main(String[] args) {
  45.         CircularQueue<Integer> queue = new CircularQueue<>(5);
  46.         queue.enqueue(1);
  47.         queue.enqueue(2);
  48.         queue.enqueue(3);
  49.         System.out.println(queue.dequeue()); // Output: 1
  50.         System.out.println(queue.getFront()); // Output: 2
  51.         System.out.println(queue.isEmpty()); // Output: false
  52.         System.out.println(queue.size()); // Output: 2
  53.     }
  54. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-2 04:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表