-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.js
82 lines (66 loc) · 1.57 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
75
76
77
78
79
80
81
82
// linked list
// print() (traversal) is O(n) time complexity where n scales with list size
// remaining methods are O(1) constant time
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
isEmpty() {
return this.head === null;
}
addToHead(data) {
const newNode = new Node(data);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
}
addToTail(data) {
const newNode = new Node(data);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
removeFromHead() {
if (this.isEmpty()) {
return null;
}
const removedData = this.head.data;
this.head = this.head.next;
if (this.head === null) {
this.tail = null;
}
return removedData;
}
print() {
let currentNode = this.head;
const elements = [];
while (currentNode !== null) {
elements.push(currentNode.data);
currentNode = currentNode.next;
}
console.log(elements.join(" -> "));
}
}
// test output:
const linkedList = new LinkedList();
linkedList.addToTail(15);
linkedList.addToTail(22);
linkedList.addToTail(31);
linkedList.print(); // Output: 15 -> 22 -> 31
linkedList.removeFromHead();
linkedList.print(); // Output: 22 -> 31