* Initialize your data structure here. Set the size of the deque to be k.
 * @param {number} k
 */
function ListNode(value) {
  this.value = value;
  this.prev = this.next = null;
}
var MyCircularDeque = function (k) {
  this.capacity = k; 
  this.length = 0; 
  const node = this.createNode();
  this.head = node;
  this.tail = node;
};
MyCircularDeque.prototype.createNode = function (value = -1) {
  return new ListNode(value);
};
 * Adds an item at the front of Deque. Return true if the operation is successful.
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertFront = function (value) {
  
  if (this.isFull()) {
    return false;
  }
  
  const node = this.createNode(value);
  
  this.head.next = node;
  node.prev = this.head;
  
  this.head = node;
  
  this.length++;
  return true;
};
 * Adds an item at the rear of Deque. Return true if the operation is successful.
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertLast = function (value) {
  
  if (this.isFull()) {
    return false;
  }
  
  this.tail.value = value;
  
  const node = this.createNode();
  
  this.tail.prev = node;
  node.next = this.tail;
  
  this.tail = node;
  
  this.length++;
  return true;
};
 * Deletes an item from the front of Deque. Return true if the operation is successful.
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteFront = function () {
  
  if (this.isEmpty()) {
    return false;
  }
  
  const temp = this.head.prev;
  
  this.head.prev = null;
  temp.next = null;
  
  this.head = temp;
  
  this.length--;
  return true;
};
 * Deletes an item from the rear of Deque. Return true if the operation is successful.
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteLast = function () {
  
  if (this.isEmpty()) {
    return false;
  }
  
  const temp = this.tail.next;
  
  temp.value = -1;
  
  this.tail.next = null;
  temp.prev = null;
  
  this.tail = temp;
  
  this.length--;
  return true;
};
 * Get the front item from the deque.
 * @return {number}
 */
MyCircularDeque.prototype.getFront = function () {
  
  return this.head.value;
};
 * Get the last item from the deque.
 * @return {number}
 */
MyCircularDeque.prototype.getRear = function () {
  
  if (this.isEmpty()) {
    return -1;
  }
  
  return this.tail.next.value;
};
 * Checks whether the circular deque is empty or not.
 * @return {boolean}
 */
MyCircularDeque.prototype.isEmpty = function () {
  return !this.length;
};
 * Checks whether the circular deque is full or not.
 * @return {boolean}
 */
MyCircularDeque.prototype.isFull = function () {
  return this.length === this.capacity;
};
评论