1. 程式人生 > >622. 設計迴圈佇列

622. 設計迴圈佇列

622.設計迴圈佇列

設計你的迴圈佇列實現。 迴圈佇列是一種線性資料結構,其操作表現基於 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 的範圍內;
  • 請不要使用內建的佇列庫。

分析: 用vector<int> 實現。

class MyCircularQueue {
private:
    int size;
    vector<int> q;

public:
    /** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) { size=k; } /** Insert an element into the circular queue. Return true if the operation is successful. */ bool enQueue(int value) { if(isFull()) return false; q.push_back(value); return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ bool deQueue() { if(isEmpty()) return false; q.erase(q.begin()); return true; } /** Get the front item from the queue. */ int Front() { if(isEmpty()) return -1; return q[0]; } /** Get the last item from the queue. */ int Rear() { if(isEmpty()) return -1; return q[q.size()-1]; } /** Checks whether the circular queue is empty or not. */ bool isEmpty() { return q.size()==0; } /** Checks whether the circular queue is full or not. */ bool isFull() { return q.size()==size; } }; /** * 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(); */