forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234-palindromeLinkedList.js
42 lines (39 loc) · 1010 Bytes
/
234-palindromeLinkedList.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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Key: find the middle of the list first
* reverse the second half and then compare it with first half
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
if (!head || !head.next) return true;
var fastHead = head;
var slowHead = head;
while (fastHead.next && fastHead.next.next) {
slowHead = slowHead.next;
fastHead = fastHead.next.next;
}
// reverse the scond half
var center = slowHead.next;
var centerNext = center.next;
slowHead.next = null;
center.next = null;
while (centerNext) {
var tmp = centerNext.next;
centerNext.next = center;
center = centerNext;
centerNext = tmp;
}
while (head && center) {
if (head.val !== center.val) return false;
head = head.next;
center = center.next;
}
return true;
};