234. 回文链表

双指针法

class Solution {
    public boolean isPalindrome(ListNode head) {

        ListNode dummyHead = new ListNode(0, head);
        ListNode slow = dummyHead;
        ListNode fast = dummyHead;

        /**
         * 快慢指针找到中间节点
         * 长度为偶数时,slow指向左区间最后一个节点
         */
        while (fast != null && fast.next != null){

            fast = fast.next.next;
            slow = slow.next;
        }

        /**
         * 将左右区间分离,然后反转右区间
         */
        ListNode next = slow.next;
        slow.next = null;
        ListNode rigthHead = reverse(next);

        /**
         * 依次比较两个区间的节点大小
         */
        while (head != null && rigthHead != null){

            if (head.val != rigthHead.val){
                return false;
            }

            head = head.next;
            rigthHead = rigthHead.next;
        }

        return true;
    }

    public ListNode reverse(ListNode head){

        ListNode prev = null;
        ListNode cur = head;

        while (cur != null){

            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }

        return prev;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/palindrome-linked-list/

posted @ 2021-12-19 18:29  振袖秋枫问红叶  阅读(32)  评论(0)    收藏  举报