基础数据结构--手动实现队列及其相关方法

队列的定义:队列其实应该是属于列表的一种,又像是俩个栈拼接形成一样来存储有序数据。队列是一种先进先出的数据结构,就像是公交车一样,前门上车后门下车.所以对于队列的操作最主要的就是俩种:对列尾部插入,队列头部删除。既入队和出对。

队列实现的属性有:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function Queue () {
// 存储数据
this.dataStore = []
// 向队尾push数据
this.enqueue = enqueue
// 从队头删除数据
this.dequeue = dequeue
// 获取对首元素
this.front = front
// 获取队尾元素
this.back = back
// 判断对列是不是空
this.empty = empty
// 显示队列中的所有元素
this.toString = toString
}
function enqueue (item) {
this.dataStore.push(item)
}
function dequeue () {
this.dataStore.shift()
}
function empty () {
return !!this.dataStore.length
}
function front () {
return this.dataStore[0]
}
function back () {
return this.dataStore[this.dataStore.length - 1]
}
function toString () {
return this.dataStore.reduce((total, curr) => {
total += curr
})
}
// 测试
var queue = new Queue()

注:队列是一种比较重要的数据结构,诸如,排队,排序问题,利用队列将是非常好的解决方式。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信