-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.LinkedList.js
More file actions
91 lines (79 loc) · 1.84 KB
/
15.LinkedList.js
File metadata and controls
91 lines (79 loc) · 1.84 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
class Node {
constructor(data, next = null) {
this.data = data
this.next = next
}
}
class LinkedList {
constructor() {
this.head = null
this.tail = null
}
append(data) {
const node = new Node(data)
if (this.tail) {
this.tail.next = node
}
if (!this.head) {
this.head = node
}
this.tail = node
}
prepend(data) {
const node = new Node(data, this.head)
this.head = node
if (!this.tail) {
this.tail = node
}
}
insertAfter(after, data) {
const found = this.find(after)
if (!found) {
return
}
found.next = new Node(data, found.next)
}
find(data) {
if (!this.head) {
return
}
let current = this.head
while (current) {
if (current.data === data) {
return current
}
current = current.next
}
}
remove(data) {
if (!this.head || !this.find(data)) {
return;
}
let current = this.head
while (current) {
if (!current.next.next && (current.next.data === data)) {
current.next = null
return;
}
if (current.data === data) {
this.head = this.head.next
return;
}
if (current.next.data === data) {
current.next = current.next.next
return;
}
current = current.next
}
}
toArray() {
let current = this.head
const result = []
while (current) {
result.push(current.data)
current = current.next
}
return result
}
}
const list = new LinkedList()