【路飞】leetcode 622. 设计循环队列

78 阅读1分钟

解法: 数组法

思路: 利用数组的方式,设计循环队列,因队列的操作表现基于 FIFO(先进先出),所以我们在删除玄素的时候需要从头部删除,具体实现:

var MyCircularQueue = function(k) {
    this.arr = new Array(k)
    this.size = k
    this.len = 0
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularQueue.prototype.enQueue = function(value) {
    if (this.len <= this.size - 1) {
        this.arr.splice(this.len, 1, value)
        this.len++
        return true
    }
    return false
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.deQueue = function() {
    if (this.len) {
        this.arr.shift()
        this.len--
        return true
    }
    return false
};

/**
 * @return {number}
 */
MyCircularQueue.prototype.Front = function() {
    if (this.len) {
        return this.arr[0]
    }
    return -1
};

/**
 * @return {number}
 */
MyCircularQueue.prototype.Rear = function() {
    if (this.len) {
        return this.arr[this.len - 1]
    }
    return -1
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.isEmpty = function() {
    return this.len === 0
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.isFull = function() {
    return this.len === this.size
};