-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpalindrome.js
71 lines (55 loc) · 1.27 KB
/
palindrome.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
// {"category": "Algorithm", "notes": "Check if a linked list is palindrome"}
/*
Implement a function to check if a linked list is a palindrome.
*/
'use strict';
export class ListNode {
constructor(element, next = null) {
this.element = element;
this.next = next;
}
isPalindrome() {
if (this.next) {
let result = {
isPalindrome: null,
node: this.next
};
this.next.isPalindromeRecursive(result);
return result.isPalindrome;
}
return false;
}
isPalindromeRecursive(result) {
if (this.next) {
this.next.isPalindromeRecursive(result);
if (result.isPalindrome !== null) {
return;
}
result.node = result.node.next;
}
if (result.node === this) {
result.isPalindrome = true;
return;
}
if (result.node.element !== this.element) {
result.isPalindrome = false;
return;
}
if (result.node.next === this) {
result.isPalindrome = true;
}
}
insert(element, after) {
let found = this.find(after);
let node = new ListNode(element, found.next);
found.next = node;
return this;
}
find(element) {
let node = this;
while (node && node.element != element) {
node = node.next;
}
return node;
}
}