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;
}
}
3. 链表(LinkedList)
链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 添加元素到链表尾部
append(element) {
const node = new Node(element);
if(!this.head) {
this.head = node;
} else {
let current = this.head;
while(current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// 在指定位置插入元素
insert(element, position) {
if(position < 0 || position > this.size) return false;
const node = new Node(element);
if(position === 0) {
node.next = this.head;
this.head = node;
} else {
let current = this.head;
let previous = null;
let index = 0;
while(index++ < position) {
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
this.size++;
return true;
}
// 删除指定位置的元素
removeAt(position) {
if(position < 0 || position >= this.size) return null;
let current = this.head;
if(position === 0) {
this.head = current.next;
} else {
let previous = null;
let index = 0;
while(index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.size--;
return current.element;
}
// 获取元素的索引
indexOf(element) {
let current = this.head;
let index = 0;
while(current) {
if(current.element === element) return index;
current = current.next;
index++;
}
return -1;
}
// 判断链表是否为空
isEmpty() {
return this.size === 0;
}
// 获取链表大小
getSize() {
return this.size;
}
// 获取链表的头部元素
getHead() {
return this.head;
}
}