1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class MyCircularQueue {
private int[] circularQueue;
private int count;
private int start;
private int end;

public MyCircularQueue(int k) {
circularQueue = new int[k];
start = 0;
end = 0;
count = 0;
}

public boolean enQueue(int value) {
if (count == circularQueue.length) {
return false;
}
circularQueue[end] = value;
end = end == circularQueue.length - 1 ? 0 : end + 1;
count += 1;
return true;
}

public boolean deQueue() {
if (count == 0) {
return false;
}
start = start == circularQueue.length - 1 ? 0 : start + 1;
count -= 1;
return true;
}

public int Front() {
if (count == 0) {
return -1;
}
return circularQueue[start];
}

public int Rear() {
if (count == 0) {
return -1;
}
int lastIdx = end == 0 ? circularQueue.length - 1 : end - 1;
return circularQueue[lastIdx];
}

public boolean isEmpty() {
return count == 0;
}

public boolean isFull() {
return count == circularQueue.length;
}
}

最基本的用array来去implement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class MyCircularQueue {
private static class Node {
private int val;
private Node next;

Node(int _val) {
this.val = _val;
this.next = null;
}
}

private int capacity;
private int count;
private Node head, tail;

public MyCircularQueue(int k) {
count = 0;
capacity = k;
head = null;
tail = null;
}

public boolean enQueue(int value) {
if (count == capacity) {
return false;
}
if (tail == null) {
head = new Node(value);
tail = head;
} else {
tail.next = new Node(value);
tail = tail.next;
}
count += 1;
return true;
}

public boolean deQueue() {
if (count == 0) {
return false;
}
head = head.next;
if (head == null) {
tail = null;
}
count -= 1;
return true;
}

public int Front() {
if (count == 0) {
return -1;
}
return head.val;
}

public int Rear() {
if (count == 0) {
return -1;
}
return tail.val;
}

public boolean isEmpty() {
return count == 0;
}

public boolean isFull() {
return count == capacity;
}
}

这个是用singly linked list去做. head和tail记录头和尾. count记录目前node个数, capacity则是容积. 需要注意的是如果head和tail重合, 当poll出去后要把head和tail都设置为null. 如果head和tail都是null, 当offer的时候要把head和tail都指向新生成的这个node.