-
Notifications
You must be signed in to change notification settings - Fork 30
/
palindrome-linked-list.js
50 lines (46 loc) · 1.04 KB
/
palindrome-linked-list.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
// Given a singly linked list, determine if it is a palindrome.
//
// Follow up:
// Could you do it in O(n) time and O(1) space?
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
if (!head || !head.next) return true;
var dev = null;
var slow = head;
var fast = head;
while (fast && fast.next && fast.next.next) {
fast = fast.next.next;
slow=slow.next;
}
slow.next = reverseList(slow.next);
slow = slow.next;
while (slow) {
if (slow.val !== head.val) {
return false;
}
slow = slow.next;
head = head.next;
}
return true;
};
var reverseList = function(head) {
var prev = null;
var next = null;
while(head !== null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
};