Repository navigation
Expand file tree
/
Copy pathLinkedList.js
More file actions
65 lines (62 loc) · 1.59 KB
/
Copy pathLinkedList.js
File metadata and controls
65 lines (62 loc) · 1.59 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
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
insertAtHead(data) {
const newNode = new LinkedListNode(data, this.head);
this.head = newNode;
this.length++;
}
getByIndex(index) {
if (index < 0 || index >= this.length) return null;
let current = this.head;
for (let i = 0; i < index; i++) {
current = current.next;
}
return current;
}
print() {
let current = this.head;
let output = "";
while (current) {
output = `${output} ${current.value} ->`;
current = current.next;
}
console.log(`${output} null`);
}
insertAtIndex(index, value) {
if (index == 0) return this.insertAtHead(value);
//previous value is the dominant here as its normal the next value to be null.
const prev = this.getByIndex(index - 1);
if (prev == null) return null;
prev.next = new LinkedListNode(value, prev.next);
this.length++;
}
removeHead() {
this.head = this.head.next;
this.length--;
}
removeAtIndex(index) {
if (index == 0) return this.removeHead();
//previous value is the dominant here as its normal the next value to be null.
const prev = this.getByIndex(index - 1);
if (prev == null) return null;
prev.next = prev.next.next;
this.length--;
}
}
class LinkedListNode {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
LinkedList.fromValues = function (...values) {
const ll = new LinkedList();
for (let i = values.length - 1; i >= 0; i--) {
ll.insertAtHead(values[i]);
}
return ll;
};
module.exports = LinkedList;