欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 【前端面试】设计循环双端队列javascript

【前端面试】设计循环双端队列javascript

2024/10/25 5:18:29 来源:https://blog.csdn.net/weixin_43342290/article/details/141863334  浏览:    关键词:【前端面试】设计循环双端队列javascript

题目

https://leetcode.cn/problems/design-circular-deque/description/
在这里插入图片描述

存储循环队列的向量空间是循环的,用通俗的话来讲,就是我们在做next或者prev操作时,不会发生溢出
取模、或者直接判断是否为0/size返回一个值。

数组实现

用函数来实现一个类,定义容量、头尾指针,和初始化数组存储

/*** @param {number} k*/
var MyCircularDeque = function(k) {this.capacity = k + 1;this.rear = this.front = 0;this.elements = new Array(k + 1).fill(0);
};

利用原型链扩展循环队列的能力


/** * @param {number} value* @return {boolean}*/
MyCircularDeque.prototype.insertFront = function(value) {if (this.isFull()) {return false;}this.front = (this.front - 1 + this.capacity) % this.capacity;this.elements[this.front] = value;return true;
};/** * @param {number} value* @return {boolean}*/
MyCircularDeque.prototype.insertLast = function(value) {if (this.isFull()) {return false;}this.elements[this.rear] = value;this.rear = (this.rear + 1) % this.capacity;return true;
};/*** @return {boolean}*/
MyCircularDeque.prototype.deleteFront = function() {
if (this.isEmpty()) {return false;}this.front = (this.front + 1) % this.capacity;return true;
};/*** @return {boolean}*/
MyCircularDeque.prototype.deleteLast = function() {
if (this.isEmpty()) {return false;}this.rear = (this.rear - 1 + this.capacity) % this.capacity;return true;
};/*** @return {number}*/
MyCircularDeque.prototype.getFront = function() {if (this.isEmpty()) {return -1;}return this.elements[this.front];
};/*** @return {number}*/
MyCircularDeque.prototype.getRear = function() {
if (this.isEmpty()) {return -1;}return this.elements[(this.rear - 1 + this.capacity) % this.capacity];
};/*** @return {boolean}*/
MyCircularDeque.prototype.isEmpty = function() {
return this.rear == this.front;
};/*** @return {boolean}*/
MyCircularDeque.prototype.isFull = function() {return (this.rear + 1) % this.capacity == this.front;
};/*** Your MyCircularDeque object will be instantiated and called as such:* var obj = new MyCircularDeque(k)* var param_1 = obj.insertFront(value)* var param_2 = obj.insertLast(value)* var param_3 = obj.deleteFront()* var param_4 = obj.deleteLast()* var param_5 = obj.getFront()* var param_6 = obj.getRear()* var param_7 = obj.isEmpty()* var param_8 = obj.isFull()*/

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com