Saturday, September 12, 2015

Palindrome Linked List

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?
Solution: O(n) time and O(1) space. 
Set fast and slow pointers to split linked list in half, reverse the last half of list and compare with the first half of list. 
/**
 * 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 || head.next == 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 head2 = slow.next;  // split the list
        slow.next = null;
        
        head2 = reverseList(head2);  // reverse second half of the list
        
        // compare two lists
        ListNode h1 = head;
        ListNode h2 = head2;
        while (h1 != null && h2 != null) {
            if (h1.val == h2.val) {
                h1 = h1.next;
                h2 = h2.next;
            } else {
                return false;
            }
        }
        
        return true;
    }
    
    public ListNode reverseList(ListNode head) {
        if (head.next == null) {
            return head;
        }
        
        ListNode p1 = head;
        ListNode p2 = head.next;
        head.next = null;
        
        while (p1 != null && p2 != null) {
            ListNode temp = p2.next;
            p2.next = p1;
            p1 = p2;
            if (temp != null) {
                p2 = temp;
            } else {
                break;
            }
        }
        
        return p2;
    }
}

No comments:

Post a Comment