How to implement a singly linked list in JavaScript

Here is one reference implementation for a singly linked list in JavaScript:

SinglyLinkedListTry in REPL
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
109
110
111
112
function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value) {
this.value = value;
this.next = null;
}
LinkedList.prototype.contains = function(value) {
if (!this.head || !this.tail) return false;
let node = this.head;
while (node) {
if (node.value === value) return true;
node = node.next;
}
return false;
};
LinkedList.prototype.indexOf = function() {
};
LinkedList.prototype.addToHead = function(value) {
const node = new Node(value);
if (!this.head && !this.tail) {
this.head = this.tail = node;
} else {
node.next = this.head;
this.head = node;
}
};
LinkedList.prototype.addToTail = function (value){
const node = new Node(value);
if (!this.head && !this.tail) {
this.head = this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
};
LinkedList.prototype.insertAfter = function(target, value) {
if (!this.head || !this.tail) return false;
let node = this.head;
const newNode = new Node(value);
while (node) {
if (node === target) {
newNode.next = node.next;
node.next = newNode;
}
node = node.next;
}
};
LinkedList.prototype.getValues = function(){
const values = [];
let node = this.head;
while (node) {
values.push(node.value)
node = node.next;
}
return values;
};
LinkedList.prototype.iterativeReverse = function(){
let current = this.head;
let prev = null;
let next = null;
// Swap head and tail
this.head = this.tail;
this.tail = current;
// change pointers iteratively
while (current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return this.tail;
};
LinkedList.prototype.recursiveReverse = function(){
const current = arguments[0] !== undefined ? arguments[0] : this.head;
const prev = arguments[1] !== undefined ? arguments[1] : null;
if (!current) {
let temp = this.head;
this.head = this.tail;
this.tail = temp;
return this.head;
}
const next = current.next;
current.next = prev;
this.recursiveReverse(next, current)
};

Test cases can be found at REPL.it