-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathlinked-list.js
79 lines (61 loc) · 1.3 KB
/
linked-list.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
export class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
export class LinkedList {
constructor() {
this.head = null;
}
pushFront(value) {
this.head = new Node(value, this.head);
}
pushBack(value) {
if (this.isEmpty()) {
this.head = new Node(value);
return;
}
let currentNode = this.head;
while (currentNode && currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = new Node(value);
}
size() {
let count = 0;
let currentNode = this.head;
while (currentNode) {
count += 1;
currentNode = currentNode.next;
}
return count;
}
search(value) {
let currentNode = this.head;
while (currentNode && currentNode.value !== value) {
currentNode = currentNode.next;
}
return Boolean(currentNode);
}
remove(value) {
if (this.isEmpty()) {
return;
}
if (this.head.value === value) {
this.head = this.head.next;
return;
}
let currentNode = this.head;
while (currentNode.next) {
if (currentNode.next.value === value) {
currentNode.next = currentNode.next.next;
return;
}
currentNode = currentNode.next;
}
}
isEmpty() {
return this.head === null;
}
}