一、队列的特点
先进先出,后进后出
二、使用类和数组封装单向队列
// 封装的栈数据类型
class Queue {
// 私有属性
#items = [];
// 弹出队列
dequeue() {
return this.#items.shift();
}
// 进入队列
enqueue(data) {
this.#items.push(data);
}
// 获取队列元素
front() {
// return this.#items[0];
return this.#items.at(0);
}
// 判断是否未空
isEmpty() {
return this.#items.length === 0;
}
// 栈的长度
size() {
return this.#items.length;
}
// 清空栈
clear() {
this.#items = [];
}
// 转换成字符串
toString(data) {
return this.#items.join(data);
}
}
三、使用类和对象封装的双向队列数据类型
// 封装的双向队列数据类型
class DeQueue {
// 私有属性
#items = {};
#lowCount = 0;
#count = 0;
// 进入队列
addBack(data) {
this.#items[this.#count] = data;
this.#count++;
}
addFront(data) {
if (this.isEmpty()) {
this.addBack(data);
} else {
if (this.#lowCount > 0) {
this.#items[this.#lowCount - 1] = data;
this.#lowCount--;
} else {
for (let i = this.#count; i > 0; i--) {
this.#items[i] = this.#items[i - 1];
}
this.#items[0] = data;
this.#count++;
}
}
}
// 弹出队列
removeFront() {
if (this.isEmpty()) return
let res = this.#items[this.#lowCount];
delete this.#items[this.#lowCount];
this.#lowCount++;
return res;
}
removeBack() {
if (this.isEmpty()) return
this.#count--;
let res = this.#items[this.#count];
delete this.#items[this.#count];
return res;
}
// 获取队列第一个元素
peekFront() {
return this.#items[this.#lowCount];
}
// 获取队列最后一个元素
peekBack() {
if (this.isEmpty()) return
return this.#items[this.#count - 1];
}
// 判断是否未空
isEmpty() {
return this.size() === 0;
}
// 栈的长度
size() {
return this.#count - this.#lowCount;
}
// 清空栈
clear() {
this.#items = {}
this.#count = 0;
this.#lowCount = 0;
}
// 转换成字符串
toString(data) {
let str = '';
for (let i = this.#lowCount; i < this.#count; i++) {
str += this.#items[i] + data;
}
return str;
}
}