-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.js
More file actions
82 lines (66 loc) · 1.45 KB
/
Copy pathlinkedList.js
File metadata and controls
82 lines (66 loc) · 1.45 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
class Node {
constructor(value, next) {
this.value = value
this.next = next
}
}
class LinkedList {
constructor(value) {
this.head = new Node(value, null)
this.tail = this.head
this.length = 1
}
prepend(value) {
let currentHead = this.head
this.head = new Node(value, currentHead)
this.length++
}
append(value) {
this.tail.next = new Node(value, null)
this.tail = this.tail.next
this.length++
}
insert(index, value) {
if (index === 0) {
this.prepend(value)
}
if (index >= this.length) {
this.append(value)
}
let insertionVertex = this.traverse(this.head, index - 1);
let holdingVertex = insertionVertex.next
insertionVertex.next = new Node(value, holdingVertex)
return this
}
remove(index){
let vertex = this.traverse(this.head, index - 1);
vertex.next = vertex.next.next;
return this;
}
traverse(node, index) {
let counter = 0
while (counter !== index) {
node = node.next
counter++
}
return node
}
printList() {
let currentNode = this.head
let list = []
while (currentNode !== null) {
list.push(currentNode.value)
currentNode = currentNode.next
}
return list
}
}
const list = new LinkedList(5)
list.append(10)
list.append(16)
console.log(list.printList())
list.insert(1, 7)
list.insert(3, 12)
console.log(list.printList());
list.remove(1)
console.log(list.printList())