中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

java循環隊列怎么實現

小億
95
2023-08-01 22:54:26
欄目: 編程語言

Java中可以使用數組或者鏈表來實現循環隊列。

  1. 使用數組實現循環隊列:
public class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;
public CircularQueue(int capacity) {
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == queue.length;
}
public void enqueue(int data) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
}
rear = (rear + 1) % queue.length;
queue[rear] = data;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = queue[front];
front = (front + 1) % queue.length;
size--;
return data;
}
}
  1. 使用鏈表實現循環隊列:
public class CircularQueue {
private static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
private Node head;
private Node tail;
private int size;
public CircularQueue() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
tail.next = head; // make it circular
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = head.data;
if (head == tail) { // only one node in the queue
head = null;
tail = null;
} else {
head = head.next;
tail.next = head; // remove the reference to the old head node
}
size--;
return data;
}
}

以上是兩種常見的循環隊列的實現方式,可以根據自己的實際需求選擇適合的實現方式。

0
巧家县| 长岛县| 凭祥市| 宜黄县| 荥经县| 卢氏县| 明光市| 宜兰县| 徐闻县| 同江市| 长宁区| 昂仁县| 顺义区| 新蔡县| 杂多县| 土默特左旗| 嘉善县| 仁布县| 曲麻莱县| 石河子市| 汾西县| 来凤县| 从化市| 茌平县| 惠来县| 彭山县| 凤翔县| 龙陵县| 东兴市| 重庆市| 霍城县| 封开县| 枣庄市| 娱乐| 韶关市| 芜湖市| 石城县| 洛南县| 万宁市| 岐山县| 青河县|