Date: 2020-06-27
前面介绍了栈,遵循 先入后出(LIFO,Last-In-First-Out)的原则。
队列(Queue)
队列遵循(FIFO,First-In-First-Out)的原则,也是计算机中常用的数据结构。
function Queue() {
this.dataStore = [] // 初始化空数组来保存列表元素
this.enqueue = enqueue // 入队
this.dequeue = dequeue // 出队
this.front = front // 查看队首元素
this.end = end // 查看队尾元素
this.clear = clear // 清空栈
}
接下来实现这些方法:
enqueue: 入队
function enqueue(el) {
this.dataStore.push(el)
}
dequeue: 出队
function dequeue(el) {
if (!this.dataStore.length) return null
return this.dataStore.shift()
}
front: 查看队首元素
function front() {
if (!this.dataStore.length) return null
return this.dataStore[0]
}
end: 查看队尾元素
function end() {
if (!this.dataStore.length) return null
return this.dataStore[this.dataStore.length - 1]
}
clear: 清空队列
function clear() {
delete this.dataStore
this.dataStore = []
}
完整代码
function Queue() {
this.dataStore = [] // 初始化空数组来保存列表元素
this.enqueue = enqueue // 入队
this.dequeue = dequeue // 出队
this.front = front // 查看队首元素
this.end = end // 查看队尾元素
this.clear = clear // 清空栈
}
function enqueue(el) {
this.dataStore.push(el)
}
function dequeue(el) {
if (!this.dataStore.length) return null
return this.dataStore.shift()
}
function front() {
if (!this.dataStore.length) return null
return this.dataStore[0]
}
function end() {
if (!this.dataStore.length) return null
return this.dataStore[this.dataStore.length - 1]
}
function clear() {
delete this.dataStore
this.dataStore = []
}