234. Palindrome Linked List

Problem:
Given a singly linked list, determine if it is a palindrome.
Analysis:
Find mid and reverse mid them compare. 
To get mid, how to find out whether fast starts from head or head.next. Suppose we have
even list: 1-> 2 -> 3 -> 4 -> null 
odd list: 1-> 2 -> 3 -> 4 -> 5 -> null
From odd list, 3 is mid no matter fast starts from where. We want to reverse 3.next. Apply this conclusion to even list, reverse mid.next, so in even list mid has to be 2 instead of 3. We can decide fast starts from head.next now. 

Solution:

class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null) return true;
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode mid = reverse(slow.next);
        
        while (mid != null) {
            if (head.val != mid.val)
                return false;
            head = head.next;
            mid = mid.next;
        }
        return true;
    }
    // because prev is null, so the tail of reversed list is null
    private ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List