-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.js
74 lines (67 loc) · 1.26 KB
/
linkedList.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
class Node {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null
}
appendToTail(value) {
if (!this.head) {
this.head = new Node(value, null);
} else {
let tail = this.head;
while (tail.next) {
tail = tail.next;
}
tail.next = new Node(value, null);
}
}
deleteNode(value) {
if (this.head.value === value) {
if (!this.head.next) {
this.head = null;
} else {
this.head = this.head.next;
}
return;
}
let node = this.head;
while (node.next) {
if (node.next.value === value) {
node.next = node.next.next;
return;
}
node = node.next;
}
}
toArray() {
const arr = [];
let node = this.head;
if (!node) return arr;
while (node.next) {
arr.push(node.value);
node = node.next;
}
arr.push(node.value);
return arr;
}
findFirstNode(value) {
let node = this.head;
while (node) {
if (node.value === value)
return node;
node = node.next;
}
}
tail() {
let node = this.head;
while (node.next) {
node = node.next;
}
return node;
}
}
module.exports = LinkedList;