JavaScript 数据结构实现
1. 栈(Stack)
栈是一种遵从后进先出(LIFO)原则的有序集合。
class Stack {
constructor() {
this.items = [];
}
// 入栈
push(element) {
this.items.push(element);
}
// 出栈
pop() {
if(this.isEmpty()) return undefined;
return this.items.pop();
}
// 查看栈顶元素
peek() {
if(this.isEmpty()) return undefined;
return this.items[this.items.length - 1];
}
// 判断栈是否为空
isEmpty() {
return this.items.length === 0;
}
// 清空栈
clear() {
this.items = [];
}
// 获取栈的大小
size() {
return this.items.length;
}
}
2. 队列(Queue)
队列是遵循先进先出(FIFO)原则的一组有序的项。
class Queue {
constructor() {
this.items = {};
this.frontIndex = 0;
this.backIndex = 0;
}
// 入队
enqueue(element) {
this.items[this.backIndex] = element;
this.backIndex++;
}
// 出队
dequeue() {
if(this.isEmpty()) return undefined;
const result = this.items[this.frontIndex];
delete this.items[this.frontIndex];
this.frontIndex++;
return result;
}
// 查看队首元素
front() {
if(this.isEmpty()) return undefined;
return this.items[this.frontIndex];
}
// 判断队列是否为空
isEmpty() {
return this.backIndex - this.frontIndex === 0;
}
// 获取队列大小
size() {
return this.backIndex - this.frontIndex;
}
// 清空队列
clear() {
this.items = {};
this.frontIndex = 0;
this.backIndex = 0;
}
}