1
+ // 实现循环队列 阿里面试题
2
+
3
+ // Runtime: 32 ms, faster than 84.47% of C++ online submissions for Design Circular Queue.
4
+ // Memory Usage: 16.5 MB, less than 72.73% of C++ online submissions for Design Circular Queue.
5
+
6
+ class MyCircularQueue
7
+ {
8
+ public:
9
+ /* * Initialize your data structure here. Set the size of the queue to be k. */
10
+ MyCircularQueue (int k) : data(k + 1 , 0 )
11
+ {
12
+ front = 0 ;
13
+ rear = 0 ;
14
+ }
15
+
16
+ /* * Insert an element into the circular queue. Return true if the operation is successful. */
17
+ bool enQueue (int value)
18
+ {
19
+ if (!isFull ())
20
+ {
21
+ rear = (rear + 1 ) % data.size ();
22
+ data[rear] = value;
23
+
24
+ return true ;
25
+ }
26
+ else
27
+ {
28
+ return false ;
29
+ }
30
+ }
31
+
32
+ /* * Delete an element from the circular queue. Return true if the operation is successful. */
33
+ bool deQueue ()
34
+ {
35
+ if (!isEmpty ())
36
+ {
37
+ front = (front + 1 ) % data.size ();
38
+ return true ;
39
+ }
40
+ else
41
+ {
42
+ return false ;
43
+ }
44
+ }
45
+
46
+ /* * Get the front item from the queue. */
47
+ int Front ()
48
+ {
49
+ if (!isEmpty ())
50
+ {
51
+ return data[(front + 1 ) % data.size ()];
52
+ }
53
+ else
54
+ {
55
+ return -1 ;
56
+ }
57
+ }
58
+
59
+ /* * Get the last item from the queue. */
60
+ int Rear ()
61
+ {
62
+ if (!isEmpty ())
63
+ {
64
+ return data[rear];
65
+ }
66
+ else
67
+ {
68
+ return -1 ;
69
+ }
70
+ }
71
+
72
+ /* * Checks whether the circular queue is empty or not. */
73
+ bool isEmpty ()
74
+ {
75
+ return rear == front;
76
+ }
77
+
78
+ /* * Checks whether the circular queue is full or not. */
79
+ bool isFull ()
80
+ {
81
+ return (rear + 1 ) % data.size () == front;
82
+ }
83
+ private:
84
+ int front; // 头部索引
85
+ int rear; // 尾部索引
86
+
87
+ vector<int > data; // 数据存储
88
+ };
89
+
90
+ /* *
91
+ * Your MyCircularQueue object will be instantiated and called as such:
92
+ * MyCircularQueue* obj = new MyCircularQueue(k);
93
+ * bool param_1 = obj->enQueue(value);
94
+ * bool param_2 = obj->deQueue();
95
+ * int param_3 = obj->Front();
96
+ * int param_4 = obj->Rear();
97
+ * bool param_5 = obj->isEmpty();
98
+ * bool param_6 = obj->isFull();
99
+ */
0 commit comments