JavaScript - 队列和双端队列
大约 1 分钟
JavaScript - 队列和双端队列
class Queue {
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
// 添加元素
enqueue(element) {
this.items[this.count] = element;
this.count += 1;
}
// 移除元素
dnqueue() {
if (this.isEmpty()) {
return undefined;
}
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount += 1;
return result;
}
// 查看队头
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.lowestCount];
}
// 获取队列长度
size() {
return this.count - this.lowestCount;
}
// 检查队列是否为空
isEmpty() {
return this.size() === 0;
}
// 清空队列
clear() {
this.items = [];
this.count = 0;
this.lowestCount = 0;
}
// toString
toString() {
if (this.isEmpty()) {
return "";
}
let objString = `${this.items[this.lowestCount]}`;
for (let i = this.lowestCount + 1; i < this.count; i += 1) {
objString += `,${this.items[i]}`;
}
return objString;
}
}
双端队列数据结构
class Deque {
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
addFront(element) {
if (this.isEmpty()) {
this.addBack(element);
} else if (this.lowestCount > 0) {
this.lowestCount -= 1;
this.items[this.lowestCount] = element;
} else {
for (let i = this.count; i > 0; i -= 1) {
this.items[i] = this.items[i - 1];
}
this.count += 1;
this.lowestCount = 0;
this.items[0] = element;
}
}
// 后端添加元素
addBack(element) {
this.items[this.count] = element;
this.count += 1;
}
// 移除前端元素
removeFront() {
if (this.isEmpty()) {
return undefined;
}
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount += 1;
return result;
}
// 移除后端元素
removeBack() {
if (this.isEmpty()) {
return undefined;
}
this.count -= 1;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
// 获取队头元素
peekFront() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.lowestCount];
}
// 获取队尾元素
peekBack() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}
// 获取队列长度
size() {
return this.count - this.lowestCount;
}
// 检查队列是否为空
isEmpty() {
return this.size() === 0;
}
// 清空队列
clear() {
this.items = {};
this.count = 0;
this.lowestCount = 0;
}
// toString
toString() {
if (this.isEmpty()) {
return "";
}
let objString = `${this.items[this.lowestCount]}`;
for (let i = this.lowestCount + 1; i < this.count; i += 1) {
objString += `,${this.items[i]}`;
}
return objString;
}
}