91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
昭苏县| 祁连县| 平乡县| 德兴市| 巴林右旗| 疏勒县| 剑川县| 古丈县| 化德县| 鹿邑县| 土默特左旗| 莲花县| 南木林县| 正镶白旗| 剑阁县| 铜川市| 汉中市| 香河县| 兰西县| 泰顺县| 高密市| 吉首市| 乐陵市| 建宁县| 繁峙县| 二手房| 达孜县| 安顺市| 闽侯县| 芒康县| 涟水县| 克拉玛依市| 兴文县| 开鲁县| 湖口县| 萨迦县| 广宗县| 福安市| 博罗县| 仁布县| 五峰|