234. 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? 

 
With extra space, add everything to a list first and then compare.
/**
 * 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;
        
        Deque<Integer> items = new ArrayDeque<Integer>();
        ListNode h = head;
        while(h != null) {
            items.add(h.val);
            h = h.next;
        }
        
        while(items.size()>1){
            Integer headVal = items.remove();
            Integer tailVal = items.removeLast();
            if(headVal != tailVal)
                return false;
        }
        return true;
    }
}

 

O(n) time and O(1) space solution. Split the linked list into to two linked list. One from head to middle, the other from tail to middle.
/**
 * 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;
        
        int l = -1;
        ListNode h = head;
        while(h != null) {
            ++l;
            h = h.next;
        }
        int middle = l/2;
        
        h = head;
        while(middle>0) {
            --middle;
            h = h.next;
        }
        
        ListNode h2 = h.next;
        h.next = null; //h points to end of first part
        
        ListNode tail = revertList(h2);
        h = head;
        while(h!=null && tail!= null)
        {
            if(h.val != tail.val)
                return false;
            h = h.next;
            tail = tail.next;
        }
        
        return true;
    }
    
    private ListNode revertList(ListNode head)
    {
        if(head == null || head.next == null)
            return head;
            
        ListNode h1 = head;
        ListNode h2 = head.next;
        while(h2 != null)
        {
            ListNode h2next = h2.next;
            h2.next = h1;
            h1 = h2;
            h2 = h2next;
        }
        head.next = null;
        return h1;
    }
}

 

 
 
 
 
posted @ 2016-04-14 13:20  新一代的天皇巨星  阅读(239)  评论(0)    收藏  举报