234. Palindrome Linked List

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?



https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand



https://www.youtube.com/watch?v=oZuR2-AKkXE



This can be solved by reversing the 2nd half and compare the two halves. Let's start with an example [1, 1, 2, 1].

In the beginning, set two pointers fast and slow starting at the head.

1 -> 1 -> 2 -> 1 -> null 
sf

(1) Move: fast pointer goes to the end, and slow goes to the middle. Ignore the mid node if the list size is odd 

1 -> 1 -> 2 -> 1 -> null 
          s          f

(2) Reverse: the right half is reversed, and slow pointer becomes the 2nd head.

1 -> 1    null <- 2 <- 1           
h                      s

(3) Compare: run the two pointers head and slow together and compare.

1 -> 1    null <- 2 <- 1             
     h            s





// Exception in thread "main" java.lang.NullPointerException
    at Solution.isPalindrome(Solution.java:18)
    at __Driver__.main(__Driver__.java:21)

// wrong 

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        if(fast != null){
            slow = slow.next; // odd, let right half smaller 
        }
        ListNode secondHalf = reverse(slow);
        ListNode firstHalf = head;
        
        while(secondHalf != null){
            if(firstHalf.val != secondHalf.val){
                return false;
            }
            firstHalf = firstHalf.next;
            secondHalf = secondHalf.next;
        }
        return true;
    }

    private ListNode reverse(ListNode head) {
      if(head == null || head.next == null){
        return head;
      }
      
      ListNode prev = null;
      ListNode next = null;
      ListNode cur = head;
      
      while(cur!= null){
        next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
      }
      return prev;
    }
}

 

posted on 2018-11-09 07:18  猪猪&#128055;  阅读(104)  评论(0)    收藏  举报

导航