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

    示例 1:
    image.png

    输入:head = [1,2,2,1]
    输出:true
    示例 2:

    输入:head = [1,2]
    输出:false

    提示:

    链表中节点数目在范围[1, 105] 内
    0 <= Node.val <= 9

    进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?


    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public boolean isPalindrome(ListNode head) {
    13. ListNode fast = head, slow = head;
    14. while (fast != null && fast.next != null) {
    15. fast = fast.next.next;
    16. slow = slow.next;
    17. }
    18. //奇数,确保slow是后半段
    19. if (fast != null) slow = slow.next;
    20. ListNode reverseNode = reverse(slow);
    21. while (reverseNode != null) {
    22. if (reverseNode.val != head.val) return false;
    23. reverseNode = reverseNode.next;
    24. head = head.next;
    25. }
    26. return true;
    27. }
    28. private ListNode reverse(ListNode head) {
    29. ListNode pre = null;
    30. while (head != null) {
    31. ListNode next = head.next;
    32. head.next = pre;
    33. pre = head;
    34. head = next;
    35. }
    36. return pre;
    37. }
    38. }

    递归

    1. class Solution {
    2. ListNode pre;
    3. public boolean isPalindrome(ListNode head) {
    4. pre = head;
    5. return recur(head);
    6. }
    7. private boolean recur(ListNode head) {
    8. if (head == null) return true;
    9. if (!recur(head.next)) return false;
    10. if (pre.val != head.val) return false;
    11. pre = pre.next;
    12. return true;
    13. }
    14. }