1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @return {boolean}
    11. */
    12. var isPalindrome = function (head) {
    13. if (!head.next) return true
    14. let slow = head,
    15. fast = head,
    16. cur = null,
    17. conut = 0
    18. // 快慢指针,step = 2,找到中间节点
    19. while (fast && fast.next) {
    20. conut++
    21. fast = fast.next.next
    22. slow = slow.next
    23. }
    24. let middle = null
    25. // 反转前半段链表
    26. for (let i = 0; i < conut; i++) {
    27. middle = head
    28. head = head.next
    29. middle.next = cur
    30. cur = middle
    31. }
    32. // 如果fast不为null,说明长度是奇数,slow需要向后移一位
    33. if(fast) {
    34. slow = slow.next
    35. }
    36. while (slow && middle) {
    37. if (middle.val !== slow.val) return false
    38. slow = slow.next
    39. middle = middle.next
    40. }
    41. return true
    42. };