#622

Design Circular Queue

specialist · 810 · lc medium +31 · 54.1% accepted · 3,835 likes · top 46%

play →

Description

Implement a circular queue (also known as a Ring Buffer) with fixed capacity k using FIFO ordering where the tail wraps back around to the head. Design the MyCircularQueue class with: MyCircularQueue(k) to initialize with capacity k; enQueue(value) to insert and return true on success; deQueue() to remove from front and return true on success; Front() and Rear() to peek at the front/back (return -1 if empty); isEmpty() and isFull() status checks. Do not use a built-in queue.

Example 1:

Input
["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output
[null, true, true, true, false, 3, true, true, true, 4]

Example 2:

Explanation
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear(); // return 3
myCircularQueue.isFull(); // return True
myCircularQueue.deQueue(); // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear(); // return 4

Code

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