javaScript实现数据结构--队列

前言

学习数据结构和算法的笔记,方便下次复习巩固

js 实现队列

链表实现队列

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function LinkedQueue() {
let Node = function (ele) {
this.ele = ele
this.next = null
}

let length = 0,
front, //队首指针
rear //队尾指针
this.push = function (ele) {
let node = new Node(ele),
temp

if (length == 0) {
front = node
} else {
temp = rear
temp.next = node
}
rear = node
length++
return true
}

this.pop = function () {
let temp = front
front = front.next
length--
temp.next = null
return temp
}

this.size = function () {
return length
}
this.getFront = function () {
return front
// 有没有什么思路只获取队列的头结点,而不是获取整个队列
}
this.getRear = function () {
return rear
}
this.toString = function () {
let string = '',
temp = front
while (temp) {
string += temp.ele + ' '
temp = temp.next
}
return string
}
this.clear = function () {
front = null
rear = null
length = 0
return true
}
}

let myQueue = new LinkedQueue()

myQueue.push(1)
myQueue.push(2)
myQueue.push(3)
myQueue.push(4)
console.log(myQueue.toString()) // 1 2 3 4
console.log(myQueue.pop()) // Node { ele: 1, next: null }
console.log(myQueue.toString()) // 2 3 4

js 线性表内置数据实现

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
function ArrayQueue() {
var arr = []
//入队操作
this.push = function (element) {
arr.push(element)
return true
}
//出队操作
this.pop = function () {
return arr.shift()
}
//获取队首
this.getFront = function () {
return arr[0]
}
//获取队尾
this.getRear = function () {
return arr[arr.length - 1]
}
//清空队列
this.clear = function () {
arr = []
}
//获取队长
this.size = function () {
return length
}
}
-------------本文结束感谢您的阅读-------------

本文标题:javaScript实现数据结构--队列

文章作者:Water

发布时间:2020年05月08日 - 15:05

最后更新:2023年08月01日 - 06:08

原始链接:https://water.buging.cn/2020/05/08/javaScript实现数据结构-队列/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!