给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

    示例 1:
    image.png
    输入:head = [1,2,2,1]
    输出:true
    示例 2:
    输入:head = [1,2]
    输出:false

    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. // 链表不能使用双指针,于是我们只能把原始链表反转再比较两者是否相同
    14. // 快慢指针,起初都指向表头,快指针一次走两步,慢指针一次走一步,遍历结束时:
    15. // 要么,slow 正好指向中间两个结点的后一个。
    16. // 要么,slow 正好指向中间结点。
    17. let slow = head, fast = head;
    18. while (fast !== null && fast.next !== null) {
    19. slow = slow.next;
    20. fast = fast.next.next;
    21. }
    22. // 判断奇偶,
    23. if (fast !== null) {
    24. // 说明链表长度为奇数
    25. slow = slow.next;
    26. }
    27. // 反转slow,再比较
    28. let left = head, right = reverse(slow);
    29. while (right !== null) {
    30. if (left.val !== right.val) {
    31. return false;
    32. }
    33. left = left.next;
    34. right = right.next;
    35. }
    36. return true;
    37. };
    38. // 反转
    39. const reverse = (head) => {
    40. let pre = null, cur = head;
    41. while (cur !== null) {
    42. let tmp = cur.next;
    43. cur.next = pre;
    44. pre = cur;
    45. cur = tmp;
    46. }
    47. return pre;
    48. }

    image.png