/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function (head) {
if (!head.next) return true
let slow = head,
fast = head,
cur = null,
conut = 0
// 快慢指针,step = 2,找到中间节点
while (fast && fast.next) {
conut++
fast = fast.next.next
slow = slow.next
}
let middle = null
// 反转前半段链表
for (let i = 0; i < conut; i++) {
middle = head
head = head.next
middle.next = cur
cur = middle
}
// 如果fast不为null,说明长度是奇数,slow需要向后移一位
if(fast) {
slow = slow.next
}
while (slow && middle) {
if (middle.val !== slow.val) return false
slow = slow.next
middle = middle.next
}
return true
};