剑指 Offer II 027. 回文链表

递归

image.png

  1. class Solution {
  2. ListNode p;
  3. public boolean isPalindrome(ListNode head) {
  4. if (head == null) return true;
  5. p = head;
  6. return helper(head);
  7. }
  8. private boolean helper(ListNode head) {
  9. if (head == null) return true;
  10. boolean res = helper(head.next);
  11. res = res && (head.val == p.val);
  12. p = p.next;
  13. return res;
  14. }
  15. }

快慢指针

  1. 使用快慢指针确定中点
  2. 反转链表
  3. 挨个比对

    1. class Solution {
    2. public boolean isPalindrome(ListNode head) {
    3. if (head == null) return true;
    4. ListNode slow = head, fast = head;
    5. while (fast != null && fast.next != null) {
    6. fast = fast.next.next;
    7. slow = slow.next;
    8. }
    9. // 奇偶判断
    10. if (fast != null) slow = slow.next;
    11. ListNode n2 = reverse(slow);
    12. while (head != null && n2 != null) {
    13. if (head.val != n2.val) return false;
    14. head = head.next;
    15. n2 = n2.next;
    16. }
    17. return true;
    18. }
    19. private ListNode reverse(ListNode head) {
    20. ListNode prev = null, p = head;
    21. while (p != null) {
    22. ListNode next = p.next;
    23. p.next = prev;
    24. prev = p;
    25. p = next;
    26. }
    27. return prev;
    28. }
    29. }