js实现简单链表

最近好颓废,什么都不想做,感觉我快成咸鱼了。。。招聘笔试又是算法数据结构,什么都不懂。。等大部分公司招聘都结束了我才悔悟,真是不知不觉,后知后觉,现在只能慢慢补了 555

用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
class Node {
constructor(data,next = null){
this.data = data
this.next = next
}
}
class Link {
constructor(){
this.head = null
this.size = 0
}
//在最后加入
add(data){
let node = new Node(data)
if (!this.head)
return this.size++,this.head = node
let currentNode = this.head
while(currentNode.next){
currentNode = currentNode.next
}
return currentNode.next = node,this.size++
}
//id范围为0到size-1,也就是所以节点
remove(id){
if (id < 0 || id > this.size - 1) return console.log('id不正确')
let currentNode = this.head
if (id === 0) return this.size--,this.head = currentNode.next
for(let i = 0; i < id - 1; i++){
currentNode = currentNode.next
}
return this.size-- ,currentNode.next = currentNode.next.next
}
//id范围为0到size,包括最开头和最末尾的节点
insert(id,data){
if (id < 0 || id > this.size) return console.log('id不正确')
let currentNode = this.head
let node = new Node(data)
if (id === 0)
return node.next = this.head,
this.head = node,
this.size++
for(let i = 0; i < id - 1; i++){
currentNode = currentNode.next
}
if(id === this.seiz)
return currentNode.next = node,
this.size++
else return node.next = currentNode.next,
currentNode.next = node,
this.size++
}
//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
}
//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
}
//打印所有节点
showall(){
let currentNode = this.head
while(currentNode){
console.log(currentNode)
currentNode = currentNode.next
}
}
}