js实现双向循环链表

JS实现双向循环链表,好像没什么技术含量555,随便写了下,觉得写了不发出来好浪费。。哈哈哈
es6还是用的不怎么习惯,要多写写,下次写一下二叉树的试试。

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Node {
constructor(data,pre,next){
this.data = data
this.pre = pre
this.next = next
}
}
class Link {
constructor(){
this.head = null
this.size = 0
}
//在最后加入
add(data){
let node = new Node(data)
if (!this.head)
return this.head = node,
this.head.pre = this.head,
this.head.next = this.head,
this.size++
let currentNode = this.head
while(currentNode.next !== this.head){
currentNode = currentNode.next
}
return currentNode.next = node,
node.pre = currentNode,
node.next = this.head,
this.head.pre = node,
this.size++
}
//id范围为0到size,包括最开头和最末尾的节点
insert(id,data){
if (id < 0 || id > this.seiz) return console.log('id不正确')
let node = new Node(data)
if (id === 0)
return node.pre = this.head.pre,
node.next = this.head,
this.head.pre.next = node,
this.head = node,
this.size++
let currentNode = this.head
for(let i = 0; i < id ; i++){
currentNode = currentNode.next
}
return node.next = currentNode,
node.pre = currentNode.pre,
currentNode.pre.next = node,
currentNode.pre = node,
this.size++
}
//id范围为0到size-1,也就是所以节点
remove(id){
if (id < 0 || id > this.size - 1) return console.log('id不正确')
if (id === 0)
return this.head.pre.next = this.head.next,
this.head.next.pre = this.head.pre,
this.head = this.head.next,
this.size--
let currentNode = this.head
for(let i = 0; i < id; i++){
currentNode = currentNode.next
}
return currentNode.pre.next = currentNode.next,
currentNode.next.pre = currentNode.pre,
this.size--
}
//id范围为0到size-1,也就是所以节点
get(id){
if (id < 0 || id > this.size - 1) return console.log('id不正确')
let currentNode = this.head
for(let i = 0; i < id; i++){
currentNode = currentNode.next
}
return currentNode.data
}
//id范围为0到size-1,也就是所以节点
set(id,data){
if (id < 0 || id > this.size - 1) return console.log('id不正确')
let currentNode = this.head
for(let i = 0; i < id; i++){
currentNode = currentNode.next
}
return currentNode.data = data
}
//打印所有节点
showall(){
let currentNode = this.head
while(currentNode.next !== this.head){
console.log(currentNode)
currentNode = currentNode.next
}
console.log(currentNode)
}
}