1. 題目
設計你的循環隊列實現。 循環隊列是一種線性數據結構,其操作表現基於 FIFO(先進先出)原則並且隊尾被連接在隊首之后以形成一個循環。它也被稱為“環形緩沖器”。
循環隊列的一個好處是我們可以利用這個隊列之前用過的空間。在一個普通隊列里,一旦一個隊列滿了,我們就不能插入下一個元素,即使在隊列前面仍有空間。但是使用循環隊列,我們能使用這些空間去存儲新的值。
你的實現應該支持如下操作:
MyCircularQueue(k): 構造器,設置隊列長度為 k 。
Front: 從隊首獲取元素。如果隊列為空,返回 -1 。
Rear: 獲取隊尾元素。如果隊列為空,返回 -1 。
enQueue(value): 向循環隊列插入一個元素。如果成功插入則返回真。
deQueue(): 從循環隊列中刪除一個元素。如果成功刪除則返回真。
isEmpty(): 檢查循環隊列是否為空。
isFull(): 檢查循環隊列是否已滿。
示例:
MyCircularQueue circularQueue = new MycircularQueue(3); // 設置長度為3
circularQueue.enQueue(1); // 返回true
circularQueue.enQueue(2); // 返回true
circularQueue.enQueue(3); // 返回true
circularQueue.enQueue(4); // 返回false,隊列已滿
circularQueue.Rear(); // 返回3
circularQueue.isFull(); // 返回true
circularQueue.deQueue(); // 返回true
circularQueue.enQueue(4); // 返回true
circularQueue.Rear(); // 返回4
提示:
所有的值都在 1 至 1000 的范圍內;
操作數將在 1 至 1000 的范圍內;
請不要使用內置的隊列庫。
2. 思路
在 隊列介紹中,我們設計了一個循環隊列,但在那個實現中,當隊列滿時, tail 指向的位置是沒有數據的,也就是數組中有一個位置是閑置浪費的,顯然當時那個思路不適合本題目。
整體思路與之前仍然是一樣的,只是需要改變判斷隊列空或者滿的條件。我們再添加一個 count 的變量,來記錄隊列中元素的個數。當元素個數等於我們最開始定義的數組長度時,隊列滿;當元素個數等於零時,隊列空。
當隊列頭或者尾索引值到達數組上限時,需要再從零開始。可以用一個除余來實現,head = (head + 1) % len,索引值就會自動進行循環。
另一個要注意的事項就是,在這樣的設計下,隊列頭索引值始終指向隊列的第一個元素,但隊列尾索引值減一才指向隊列的最后一個元素,而且當隊尾索引值為零時,其”減一“后應該指向數組的最后一個元素。
class MyCircularQueue {
private:
int *data; // 存放循環隊列的數據
int head; // 循環隊列頭
int tail; // 循環隊列尾
int len; // 循環隊列的最大長度
int count; // 循環隊列的元素個數
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data = new int[k];
head = 0;
tail = 0;
len = k;
count = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if (isFull()) //循環隊列滿
{
return false;
}
else // 插入元素到隊尾,隊尾索引值增一,元素個數增一
{
data[tail] = value;
count++;
tail = (tail + 1) % len;
return true;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty()) //循環隊列空
{
return false;
}
else // 隊頭索引值增一,元素個數減一
{
head = (head + 1) % len;
count--;
return true;
}
}
/** Get the front item from the queue. */
int Front() {
if (isEmpty()) //循環隊列空
{
return -1;
}
else
{
return data[head];
}
}
/** Get the last item from the queue. */
int Rear() {
if (isEmpty()) //循環隊列空
{
return -1;
}
// 隊尾元素位於隊尾索引值減一的位置,但若隊尾循環到索引 0 的位置,隊尾元素位於數組最后
else
{
int temp = tail == 0 ? (len-1) : (tail-1);
return data[temp];
}
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return count == 0; // 隊列元素個數為零,隊列空
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return count == len; // 隊列元素個數為數組最大長度,隊列滿
}
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* bool param_1 = obj.enQueue(value);
* bool param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* bool param_5 = obj.isEmpty();
* bool param_6 = obj.isFull();
*/
獲取更多精彩,請關注「seniusen」!