LeetCode-Palindrome Linked List

LiBlog發表於2016-09-12

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

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

Analysis:

1. Use slow+fast pointers to find out the median point.

2. Reverse the later half of list in-place.

3. Compare the two half lists.

4. (if needed), reverse the later half again to get the list back to original.

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head==null) return true;
        if (head.next==null) return true;
        
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode p1 = head, p2 = head;
        while (p2.next!=null && p2.next.next!=null){
            p1 = p1.next;
            p2 = p2.next.next;
        }
        
        ListNode preHead2 = p1;
        reverseList(preHead2);
        p1 = preHead.next;
        p2 = preHead2.next;
        
        while (p2!=null){
            if (p1.val!=p2.val){
                return false;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        return true;
    }
    
    public void reverseList(ListNode preHead){
        ListNode cur = preHead.next;
        while (cur.next!=null){
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = preHead.next;
            preHead.next = next;
        }
    }
}

 

相關文章