Leetcode - Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

[分析] 利用two pointers 方式找出链表的中间节点,接着翻转后半段链表,最后比较前后两半,如果完全相同则满足回文性质。注意到比较前后两半时以后半段长度为准,因为链表长度为奇数时,前半段会多一个节点。

public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
            return true;
        if (head.next.next == null)
            return head.val == head.next.val ? true : false;
        // split input list
        ListNode p = head, q = head;
        while (q != null) {
            if (q.next != null) {
                if (q.next.next != null) {
                    p = p.next;
                    q = q.next.next;
                } else { // size is even
                    break;
                }
            } else { // size is odd
                break;
            }
        }
        
        // reverse second half
        ListNode prev = null, curr = p.next, next = null;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        
        // check if is palindrome
        q = prev;
        p = head;
        while (q != null) {
            if (p.val != q.val) return false;
            p = p.next;
            q = q.next;
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode)