這是在看leetcode
上的一個入門的數據結構,題目以下:javascript
設計你的循環隊列實現。 循環隊列是一種線性數據結構,其操做表現基於 FIFO(先進先出)原則而且隊尾被鏈接在隊首以後以造成一個循環。它也被稱爲「環形緩衝器」。 循環隊列的一個好處是咱們能夠利用這個隊列以前用過的空間。在一個普通隊列裏,一旦一個隊列滿了,咱們就不能插入下一個元素,即便在隊列前面仍有空間。可是使用循環隊列,咱們能使用這些空間去存儲新的值。 你的實現應該支持以下操做:java
想要實現上面的功能,其實主要就是判斷循環隊列是否爲空isEmpty
,是否已滿isFull
,這裏咱們使用兩個指針來表示隊首(head
)和隊尾的指針(tail
)。假設初始化的時候兩個指針的值都是-1
。那麼顯然是否爲空的判斷條件就是兩個指針都是-1
的時候。數據結構
isEmpty
實現以下:this
/** * Checks whether the circular queue is empty or not. * @return {boolean} */
MyCircularQueue.prototype.isEmpty = function() {
return this.tail === -1 && this.head === -1
};
複製代碼
當隊列滿的時候,則爲指針的下一個地址應該等於頭指針的位置:spa
isFull
實現以下:prototype
/** * Checks whether the circular queue is full or not. * @return {boolean} */
MyCircularQueue.prototype.isFull = function() {
return (this.tail + 1)%this.size === this.head
};
複製代碼
總體代碼以下:設計
/** * Initialize your data structure here. Set the size of the queue to be k. * @param {number} k */
var MyCircularQueue = function(k) {
this.size = k
this.head = -1
this.tail = -1
this.data = []
};
/** * 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()) {
return false
}
if (this.isEmpty()) {
this.head = 0
}
this.tail = (this.tail + 1)%this.size
this.data[this.tail] = value
return true
};
/** * Delete an element from the circular queue. Return true if the operation is successful. * @return {boolean} */
MyCircularQueue.prototype.deQueue = function() {
if (!this.isEmpty()) {
if (this.tail === this.head) {
this.tail = -1
this.head = -1
} else {
this.head = (this.head + 1)%this.size
}
return true
}
return false
};
/** * Get the front item from the queue. * @return {number} */
MyCircularQueue.prototype.Front = function() {
return this.head === -1? -1 : this.data[this.head]
};
/** * Get the last item from the queue. * @return {number} */
MyCircularQueue.prototype.Rear = function() {
return this.tail === -1 ? -1 : this.data[this.tail]
};
/** * Checks whether the circular queue is empty or not. * @return {boolean} */
MyCircularQueue.prototype.isEmpty = function() {
return this.tail === -1 && this.head === -1
};
/** * Checks whether the circular queue is full or not. * @return {boolean} */
MyCircularQueue.prototype.isFull = function() {
return (this.tail + 1)%this.size === this.head
};
MyCircularQueue.createNew = function(k) {
return new MyCircularQueue(k)
};
/** * Your MyCircularQueue object will be instantiated and called as such: * var obj = Object.create(MyCircularQueue).createNew(k) * var param_1 = obj.enQueue(value) * var param_2 = obj.deQueue() * var param_3 = obj.Front() * var param_4 = obj.Rear() * var param_5 = obj.isEmpty() * var param_6 = obj.isFull() */
複製代碼