622. Design Circular Queue - Medium
前往題目
想法
- 自創
node
組成linkedlist
思路
enQueue: 檢查是否已滿,未滿時可以加入新的node
,如果是唯一一個,頭尾都是相同的node **deQueue**: 如果為空就
false,否則彈出
head`,並且大小減一
Code
class MyCircularQueue {
int size;
int maxSize;
Node head;
Node tail;
public MyCircularQueue(int k) {
size = 0;
maxSize = k;
head = null;
tail = null;
}
public boolean enQueue(int value) {
// Full already
if (isFull()) return false;
// Declare the new node
Node newNode = new Node(value);
// Add to the empty queue
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
++size;
return true;
}
public boolean deQueue() {
// Empty already
if (isEmpty()) return false;
head = head.next;
--size;
return true;
}
public int Front() {
return isEmpty() ? -1 : head.val;
}
public int Rear() {
return isEmpty() ? -1 : tail.val;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == maxSize;
}
private class Node {
Node next;
int val;
public Node(int val) {
this.next = null;
this.val = val;
}
}
}
622. Design Circular Queue - Medium
https://f88083.github.io/2024/09/30/622-Design-Circular-Queue-Medium/