-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlinkedList.js
More file actions
116 lines (115 loc) · 2.92 KB
/
linkedList.js
File metadata and controls
116 lines (115 loc) · 2.92 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
class linkedList {
constructor() {
this.length = 0
this.head = null
}
append(data) {
const newNode = new Node(data)
if (this.length === 0) {
this.head = newNode.data
} else {
// 当 currentNode.next 不为空时,
// 循序依次找最后一个节点,即节点的 next 为 null 时
let currentNode = this.head
while (currentNode.next !== null) {
currentNode = currentNode.next
}
currentNode.next = newNode
this.next = newNode
}
this.length++
}
insert(position, data) {
if (position < 0 || position > this.length) return false
const newNode = new Node(data);
if (position === 0) {
newNode.next = this.head
this.head = newNode
} else {
let currentNode = this.head
let previousNode = null //head 的 上一节点为 null
let index = 0
while (index++ < position) {
previousNode = currentNode
currentNode = currentNode.next
}
// 在当前节点和当前节点的上一节点之间插入新节点,即它们的改变指向
newNode.next = currentNode
previousNode.next = newNode
}
this.length++
}
getData(position) {
if (position < 0 || position > this.length) return false
let currentNode = this.head
let index = 0
while (index++ < position) {
currentNode = currentNode.next
}
return currentNode.data
}
indexOf(data) {
let currentNode = this.head
let index = 0
while (currentNode) {
if (currentNode.data === data) {
return index
}
currentNode = currentNode.next
index++
}
}
update(position, data) {
if (position < 0 || position > this.length) return false
let currentNode = this.head
let index = 0
while (index++ < position) {
currentNode = currentNode.next
}
currentNode.data = data
return currentNode
}
removeAt(position) {
if (position < 0 || position > this.length) return null
let currentNode = this.head
if (position === 0) {
this.head = currentNode.next
} else {
let previousNode = null
let index = 0
while (index++ < position) {
previousNode = currentNode
currentNode = currentNode.next
}
// 巧妙之处,让上一节点的 next 指向到当前的节点的 next,相当于删除了当前节点
previousNode.next = currentNode.next
}
this.length--
return currentNode
}
// remove(data) 删除指定 data 的节点,并返回删除的那个节点
remove(data) {
return this.removeAt(this.indexOf(data));
}
size() {
return this.length
}
isEmpty() {
return this.length === 0
}
toString() {
let currentNode = this.head
let result = ''
while (currentNode) {
result += currentNode.data
currentNode = currentNode.next
}
return result
}
}