-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathlinked-list.js
110 lines (84 loc) · 1.82 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Node containing the data and reference to next node
class Node {
constructor(data, next) {
this.data = data
this.next = next
}
}
// Class to hold our data structure
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
// Complexity: O(1)
prepend(value) {
const newNode = new Node(value, this.head);
this.head = newNode;
this.tail = this.tail ? this.tail : newNode;
return this;
}
// Complexity: O(1)
append(value) {
const newNode = new Node(value);
// If the linked list is empty
if (!this.head) {
this.head = newNode;
this.tail = newNode;
return;
}
// Make the last item refer to the newly added node
this.tail.next = newNode;
// Make the newly added node the last/tail node
this.tail = newNode;
}
// Complexity: O(n)
traverse() {
let currentNode = this.head;
while (currentNode) {
console.log(currentNode.data);
currentNode = currentNode.next;
}
}
// Complexity: O(n)
find(value) {
let currentNode = this.head;
while (currentNode) {
if (currentNode.data === value) {
return currentNode;
}
currentNode = currentNode.next;
}
return null;
}
// Complexity: O(1)
deleteHead() {
if (!this.head) {
return;
}
if (this.head.next) {
this.head = this.head.next;
} else {
this.head = null;
this.tail = null;
}
}
toArray() {
const items = [];
let currentNode = this.head;
while (currentNode) {
items.push(currentNode.data);
currentNode = currentNode.next;
}
return items;
}
}
const list = new LinkedList();
list.append(4);
list.append(6);
list.append(2);
console.log(list.toArray());
list.prepend(1);
console.log(list.toArray());
list.find(6);
list.deleteHead();