How to check if a linked list is a palindrome in JavaScript

Here are two ways to check if a linked list is a palindrome:

isPalindromeTry 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
function isPalindrome(list) {
const reversed = reverseAndClone(list);
return isEqual(list, reversed);
}
function reverseAndClone(node) {
let head = null;
while (node) {
const copy = new Node(node.data);
copy.next = head;
head = copy;
node = node.next;
}
return head;
}
function isEqual(one, two) {
while (one && two) {
if (one.data !== two.data) {
return false;
}
one = one.next;
two = two.next;
}
return one === null && two === null;
}
// Uses a set to determine whether list is a palindrome
function isPalindromeAlternate(list) {
const set = new Set();
let current = list;
while (current) {
if (set.has(current.data)) {
set.delete(current.data);
} else {
set.add(current.data);
}
current = current.next;
}
return set.size <= 1;
}
// Uncomment to use the alternate solution
// isPalindrome = isPalindromeAlternate;
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.addToTail = function(data) {
const end = new Node(data);
let current = this;
while (current.next !== null) {
current = current.next;
}
current.next = end;
return end;
};

Tests can be found at REPL.it