设计循环双端队列

94 阅读1分钟

要求

设计实现双端队列。 你的实现需要支持以下操作:

MyCircularDeque(k):构造函数,双端队列的大小为k。

insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。

insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。

deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。

deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。

getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。

getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。

isEmpty():检查双端队列是否为空。

isFull():检查双端队列是否满了。

思路

思路与本人上一篇文章思路一致,不再赘述

代码

var MyCircularDeque = function (k) {
    // 定义一个数组
    this.Queue = Array(k + 1);
    // 创建一个头指针,一个尾指针
    this.front = 0;
    this.rear = 0;
    // 数组最大容量
    this.max = k;
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertFront = function (value) {
    if (this.isFull()) return false;
    // this.Queue[(this.front - 1 + this.max + 1) % (this.max + 1)] = value;
    this.Queue[(this.front + this.max) % (this.max + 1)] = value;
    // this.front = (this.front - 1 + this.max + 1) % (this.max + 1);
    this.front = (this.front + this.max) % (this.max + 1);
    return true;
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertLast = function (value) {
    if (this.isFull()) return false;
    this.Queue[this.rear] = value;
    this.rear = (this.rear + 1 + this.max + 1) % (this.max + 1);
    return true;
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteFront = function () {
    if (this.isEmpty()) return false;
    this.front = (this.front + 1 + this.max + 1) % (this.max + 1)
    return true;
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteLast = function () {
    if (this.isEmpty()) return false;
    // return this.rear = (this.rear - 1 + this.max + 1) % (this.max + 1)
    this.rear = (this.rear + this.max) % (this.max + 1);
    return true;
};

/**
 * @return {number}
 */
MyCircularDeque.prototype.getFront = function () {
    if (this.isEmpty()) return -1;
    return this.Queue[this.front];
};

/**
 * @return {number}
 */
MyCircularDeque.prototype.getRear = function () {
    if (this.isEmpty()) return -1;
    // return this.Queue[(this.rear - 1 + this.max + 1) % (this.max + 1)];
    return this.Queue[(this.rear + this.max) % (this.max + 1)];
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.isEmpty = function () {
    // 判断头指针与尾指针的下标是否一致,一致,即数组为空
    return this.rear - this.front == 0;
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.isFull = function () {
    // 尾指针减头指针,得到的数是否等于k值,若等于k值,即数组已满
    // 但尾指针有可能小于头指针,所以需要求余
    return ((this.rear - this.front + this.max + 1) % (this.max + 1)) == this.max;
};