1 class MyCircularQueue:
2
3 def __init__(self, k: int):
4 """
5 Initialize your data structure here. Set the size of the queue to be k.
6 """
7 self.queue = [0]*(k+1) #牺牲一个存储空间
8 self.head = 0
9 self.tail = 0
10
11 def enQueue(self, value: int) -> bool:
12 """
13 Insert an element into the circular queue. Return true if the operation is successful.
14 """
15 if self.isFull():
16 return False
17 else:
18 self.queue[self.tail] = value
19 self.tail = (self.tail+1)%len(self.queue)
20 return True
21
22
23 def deQueue(self) -> bool:
24 """
25 Delete an element from the circular queue. Return true if the operation is successful.
26 """
27 if self.tail == self.head:
28 return False
29 else:
30 self.head = (self.head+1)%len(self.queue)
31 return True
32
33
34 def Front(self) -> int:
35 """
36 Get the front item from the queue.
37 """
38 if not self.isEmpty():
39 return self.queue[self.head]
40 else:
41 return -1 #因为只存储正数,且返回值为 int 我只能写 -1 了,如果有需要可以根据需要修改这里的返回值
42
43
44 def Rear(self) -> int:
45 """
46 Get the last item from the queue.
47 """
48 if not self.isEmpty():
49 return self.queue[(self.tail-1+len(self.queue))%len(self.queue)]
50 else:
51 return -1 #因为只存储正数,且返回值为 int 我只能写 -1 了,如果有需要可以根据需要修改这里的返回值
52
53
54 def isEmpty(self) -> bool:
55 """
56 Checks whether the circular queue is empty or not.
57 """
58 return self.head == self.tail
59
60
61 def isFull(self) -> bool:
62 """
63 Checks whether the circular queue is full or not.
64 """
65 return (self.tail+1)%len(self.queue) == self.head
66