数据结构篇——队列

队列用于存储按顺序排列的数据,是一种先进先出的数据结构,最后入栈的元素反而被优先处理

应用场景

  • 提交操作系统执行的一系列进程
  • 打印任务池
  • 模拟银行的仿真系统
  • 等等
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function Queue() {
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
this.toString = toString;
this.empty = empty;
}
// 向队尾添加一个元素
function enqueue(element){
this.dataStore.push(element)
}

// 删除队尾元素
function dequeue(){
return this.dataStore.shift()
}

// 读取队首、队尾元素
function front(){
return this.dataStore[0]
}
function back(){
return this.dataStore[this.dataStore.length-1]
}

function toString(){
let str = ''
for(let i = 0; i < this.dataStore.length; ++i){
str += this.dataStore[i] + '\n'
}
return str
}

function empty(){
if(this.dataStore.length == 0){
return true
}else{
return false
}
}

// 测试代码
let q = new Queue()
q.enqueue('a')
q.enqueue('b')
q.enqueue('c')
console.log(q.toString())
q.dequeue()
console.log(q.toString())
console.log(q.front())
console.log(q.back())