234. Palindrome Linked List

Description

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

Solution

Fast-slow-pointer & reverse list, O(n), S(1)

把链表拆成两半,second链表做反转,然后比较first和second是否相等(注意长度可能会差一位)即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode secondHead = slow.next;
        slow.next = null;
        secondHead = reverse(secondHead);
        
        while (head != null && secondHead != null && head.val == secondHead.val) {
            head = head.next;
            secondHead = secondHead.next;
        }
        
        return head == null || secondHead == null;
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

你可能感兴趣的:(234. Palindrome Linked List)