LeetCode刷题,设计循环队列(622)

1,094 阅读1分钟

循环队列

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”

解题代码

var MyCircularQueue = function(k) {
  this.queue = new Array(k); // 创建k个大小的队列长度
  this.head = 0; // 头指针
  this.tail = 0; // 尾指针
  this.cnt = 0; // 当前队列中元素数量
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularQueue.prototype.enQueue = function(value) {
  if (this.isFull()) return false;
  this.queue[this.tail] = value;
  this.tail = (this.tail + 1) % this.queue.length; // 尾指针向后走一步,如果tail+1 = 队列长度,直接赋值为0
  this.cnt += 1; // 元素数量+1
  return true;
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.deQueue = function() {
  if (this.isEmpty()) return false;
  this.head = (this.head + 1) % this.queue.length; // 头指针往后走一步。
  this.cnt -= 1; 
  return true;
};

/**
 * @return {number}
 */
MyCircularQueue.prototype.Front = function() {
  if (this.isEmpty()) return -1;
  return this.queue[this.head];
};

/**
 * @return {number}
 *///获取最后一个元素
MyCircularQueue.prototype.Rear = function() {
  if (this.isEmpty()) return -1;
  let ind = this.tail - 1; // tail指向的是尾部元素的后一位,所以 - 1;
  if (ind === -1) ind = this.queue.length - 1; //如果当前tail指向0,那么应该重新赋值为队列最后一位
  return this.queue[ind]; // 或者 this.queue[(this.tail - 1 + this.queue.length) % this.queue.length]
};

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

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.isFull = function() {
  return this.cnt === this.queue.length;
};

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * var obj = new MyCircularQueue(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()
 */