分享一下之前在LeetCode上做的一個題:
實現循環隊列:
設計你的循環隊列實現。 循環隊列是一種線性數據結構,其操作表現基於 FIFO(先進先出)原則並且隊尾被連接在隊首之後以形成一個循環。它也被稱爲“環形緩衝器”。
循環隊列的一個好處是我們可以利用這個隊列之前用過的空間。在一個普通隊列裏,一旦一個隊列滿了,我們就不能插入下一個元素,即使在隊列前面仍有空間。但是使用循環隊列,我們能使用這些空間去存儲新的值。
- MyCircularQueue(k): 構造器,設置隊列長度爲 k 。
- Front: 從隊首獲取元素。如果隊列爲空,返回 -1 。
- Rear: 獲取隊尾元素。如果隊列爲空,返回 -1 。
- enQueue(value): 向循環隊列插入一個元素。如果成功插入則返回真。
- deQueue(): 從循環隊列中刪除一個元素。如果成功刪除則返回真。
- isEmpty(): 檢查循環隊列是否爲空。
- isFull(): 檢查循環隊列是否已滿。
/**
* Initialize your data structure here. Set the size of the queue to be k.
* @param {number} k
*/
var MyCircularQueue = function (k) {
this.data = {};
this.head = 0;
this.tail = 0;
this.nextAddIndex = 0;
this.lenght = k;
};
/**
* Insert an element into the circular queue. Return true if the operation is successful.
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function (value) {
if (this.isFull()) {
console.error("隊列已滿!")
return false
}
this.data[this.nextAddIndex] = value;
this.tail = this.nextAddIndex;
this.nextAddIndex++;
if (this.nextAddIndex >= this.lenght) {
this.nextAddIndex = 0
}
return true
};
/**
* Delete an element from the circular queue. Return true if the operation is successful.
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function () {
if (Object.keys(this.data).length ==0) {
return false
}
delete this.data[this.head];
this.head++
if (this.head >= this.lenght) {
this.head = 0
}
return true
};
/**
* Get the front item from the queue.
* @return {number}
*/
MyCircularQueue.prototype.Front = function () {
if (Object.keys(this.data).length ==0) {
return -1
}
return this.data[this.head]
};
/**
* Get the last item from the queue.
* @return {number}
*/
MyCircularQueue.prototype.Rear = function () {
if (Object.keys(this.data).length ==0) {
return -1
}
return this.data[this.tail]
};
/**
* Checks whether the circular queue is empty or not.
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function () {
var len = Object.keys(this.data).length
return len == 0 ? true : false
};
/**
* Checks whether the circular queue is full or not.
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function () {
var len = Object.keys(this.data).length
return len == this.lenght ? true : false
};
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