-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.js
50 lines (44 loc) · 1.03 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
class Node {
constructor(element) {
this.element = element
this.next = null
}
}
class LinkedList {
constructor() {
this.head = new Node('head')
}
find(item) {
let currentNode = this.head
while (currentNode.element !== item) {
currentNode = currentNode.next
}
return currentNode
}
insert(newElement, item) {
const newNode = new Node(newElement)
const findNode = this.find(item)
newNode.next = findNode.next
findNode.next = newNode
}
findPrevious(item) {
let currentNode = this.head
while (currentNode.next && currentNode.next.element !== item) {
currentNode = currentNode.next
}
return currentNode
}
remove(item) {
let previousNode = this.findPrevious(item)
if (previousNode) {
previousNode.next = previousNode.next.next
}
}
}
const linkedList = new LinkedList()
linkedList.insert('apple', 'head')
console.log(linkedList)
linkedList.insert('strawberry', 'apple')
console.log(linkedList)
linkedList.remove('apple')
console.log(linkedList)