lyshine
V2EX  ›  问与答

循环队列求大佬指点, 我知道我很弱 0.0

  •  
  •   lyshine · May 28, 2019 · 1734 views
    This topic created in 2564 days ago, the information mentioned may be changed or developed.

    用 js 实现了一个循环队列的, 代码如下. 可是老是通不过测试, 我真的不知道自己错在哪里. 衰啊

    /**
     * Initialize your data structure here. Set the size of the queue to be k.
     * @param {number} k
     */
    var MyCircularQueue = function (k) {
        if (k == undefined) {
            k = 0;
        }
        this.k = k;
        this.p_head = 0;
        this.p_tail = 0;
        this._data = new Array(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() == true) {
            return false
        }
        this.p_tail = this.p_tail % this.k;
        this._data[this.p_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() == true) {
            return false
        }
        this.p_head++;
        this.p_head = this.p_head % 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.p_head];
    };
    
    /**
     * Get the last item from the queue.
     * @return {number}
     */
    MyCircularQueue.prototype.Rear = function () {
        if (this.isEmpty() == true) {
            return false
        }
        // console.log(this._data[this.p_tail-1]);
        return this._data[this.p_tail];
    };
    
    /**
     * Checks whether the circular queue is empty or not.
     * @return {boolean}
     */
    MyCircularQueue.prototype.isEmpty = function () {
        return this.p_head == this.p_tail;
    };
    
    /**
     * Checks whether the circular queue is full or not.
     * @return {boolean}
     */
    MyCircularQueue.prototype.isFull = function () {
        return (this.p_tail + 1) % this.k == this.p_head;
    };
    
    1 replies    2019-05-28 15:49:58 +08:00
    lyshine
        1
    lyshine  
    OP
       May 28, 2019
    各位大佬如果不想找, 能给个清晰的实现思路吗. 我感觉自己还是思路混乱
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5773 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 02:48 · PVG 10:48 · LAX 19:48 · JFK 22:48
    ♥ Do have faith in what you're doing.