js 实现的循环队列

在 leetcode 上的题目. 实现一个循环队列, 我的实现如下

 /**
 * Initialize your data structure here. Set the size of the queue to be k.
 * @param {number} k
 */
var MyCircularQueue = function(k) {
    // 长度需要限制, 来达到空间的利用. k 代表空间的长度
    this.k = k;
    this._data = new Array(k);
    // 指向首元素
    this.font = 0;
    // 指向准备插入元素的位置
    this.rear = 0;

};

/**
 * 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() == true) {
        return false
    }
    this.rear = this.rear % this.k;
    this._data[this.rear++] = 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()){
        return false;
    }
    this.font++;
    this.font = this.font % this.k;
    return true;
};

/**
 * Get the front item from the queue.
 * @return {number}
 */
MyCircularQueue.prototype.Front = function() {
    if (this.isEmpty() == true) {
        return false;
    }
    return this._data[this.font];
};

/**
 * Get the last item from the queue.
 * @return {number}
 */
MyCircularQueue.prototype.Rear = function() {
    if (this.isEmpty() == true) {
        return false;
    }
    this._data[this.tail - 1];
};

/**
 * Checks whether the circular queue is empty or not.
 * @return {boolean}
 */
MyCircularQueue.prototype.isEmpty = function() {
    return this.font == this.rear - 1;
};

/**
 * Checks whether the circular queue is full or not.
 * @return {boolean}
 */
MyCircularQueue.prototype.isFull = function() {
    // return (this.rear + 1) % this.k == this.font;
    return this.rear % this.k == this.font;
};




测试通不过, 但是感觉自己的算法实现的没问题啊. 不知道哪里出错了

给为大佬如果嫌麻烦, 能否给个清晰的思路, 感觉还是自己的思路不清晰

阅读 2.1k
1 个回答

刚创建就是满的?

var test = new MyCircularQueue(10)
//undefined
test.isEmpty()
//false
test.isFull()
//true

每次插入一个元素后rear+1,那么连续插入k个之后 rear%k又回到原点了,跟初始条件是一样的,根据这个判断是否是满的显然是不行的

可以加一个size属性来记录元素数量,添加成功的时候size+1,删除成功的时候size-1,是满还是空直接根据size判断, font和rear可以去掉一个,根据size和另一个算出来。

以下是与功能实现无关的建议


建议取模操作在赋值的时候进行,保证rear和font的值永远是小于k的,而不是在每个引用的地方去做一次取模。还有就是个人觉得在可以保证返回值只有布尔型的情况下,if(isFull()==true)这种写法很多余

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题