亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
崇阳县| 城固县| 慈溪市| 炎陵县| 淅川县| 安义县| 盐山县| 阳朔县| 繁昌县| 广安市| 鹤岗市| 象州县| 北辰区| 淮南市| 娄底市| 皋兰县| 唐河县| 江永县| 花垣县| 盐津县| 绥江县| 昌都县| 纳雍县| 石城县| 仪征市| 清水河县| 当涂县| 鸡东县| 新泰市| 西乌珠穆沁旗| 宜黄县| 霸州市| 普定县| 赤壁市| 海淀区| 阿坝| 吉水县| 修文县| 启东市| 盐山县| 庆云县|