# 数据结构介绍
- 数组:Array
- 堆栈:Stack
- 队列:Queue
- 链表:Linked Lists
- 树:Trees
- 图:Graphs
- 字典树:Trie
- 散列表(哈希表):Hash Tables
我们可以先大体感知一下各种数据结构之间的关系:
栈和队列是类似数组的结构,非常多的初级题目要求用数组实现栈和队列,它们在插入和删除的方式上和数组有所差异,但是实现还是非常简单的;- 链表、树和图这种数据结构的特点是,
其节点需要引用其他节点,因此在增/删时,需要注意对相关前驱和后继节点的影响; - 可以
从堆栈和队列出发,构建出链表; - 树和图最为复杂,但它们本质上
扩展了链表的概念; 散列表的关键是理解散列函数,明白依赖散列函数实现保存和定位数据的过程;- 直观上认为,
链表适合记录和存储数据;哈希表和字典树在检索数据以及搜索方面有更大的应用场景。
# 堆栈和队列
栈和队列是一种操作受限的线性结构,它们非常简单,虽然 JavaScript 并没有原生内置这样的数据结构,但是我们可以轻松地模拟出来
栈的实现,后进先出 LIFO(Last in、First out):
class Stack {
constructor(...args) {
// 使用数组进行模拟
this.stack = [...args]
}
push(...items) {
// 入栈
return this.stack.push(... items)
}
pop() {
// 出栈,从数组尾部弹出一项
return this.stack.pop()
}
peek() {
return this.isEmpty()
? undefined
: this.stack[this.size() - 1]
}
isEmpty() {
return this.size() == 0
}
size() {
return this.stack.length
}
}
@前端进阶之旅: 代码已经复制到剪贴板
队列的实现,先进先出 FIFO(First in、First out),“比葫芦画瓢”即可:
class Queue {
constructor(...args) {
// 使用数组进行模拟
this.queue = [...args]
}
enqueue(...items) {
// 入队
return this.queue.push(... items)
}
dequeue() {
// 出队
return this.queue.shift()
}
front() {
return this