-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkList.js
77 lines (75 loc) · 1.87 KB
/
LinkList.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
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkList {
constructor() {
this.head = new ListNode('head');
}
find (value) {
let current = this.head;
while (current.value !== value) {
if (current.next) {
current = current.next;
} else {
return -1;
}
}
return current;
}
insert (newValue, value = null) {
let newNode = new ListNode(newValue);
if (value !== null) {
let node = this.find(value);
if (node) {
newNode.next = node.next;
node.next = newNode;
} else {
new Error('not found the value:' + value);
return false
}
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
}
forEach (fn) {
let current = this.head;
let i = 0
while (current.next !== null) {
current = current.next;
fn(current, i);
i++;
}
}
remove (value) {
let prev = this.head;
let current = this.head.next;
while (current.value !== value && current !== null) {
prev = current;
current = current.next;
}
if (current) {
prev.next = current.next;
return current;
} else {
new Error('not found the value:' + value);
return false;
}
}
get length () {
let length = 0;
let current = this.head
while (current.next) {
current = current.next;
length++;
}
return length;
}
}
module.exports = LinkList;