234. Palindrome Linked List
Tags: ‘Linked List’, ‘Two Pointers’
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
Reverse second half, then compare
class Solution {
public boolean isPalindrome(ListNode head) {
// linear time and constant space
// Reverse second half, compare. Draw a diagram if not clear(odd 3, even 4)
// 99% 60%
if (head == null || head.next == null) return true;
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
} // slow should be in the middle or begin of second half;
slow = reverse(slow);
while(head != null && slow != null) {
if (head.val != slow.val) return false;
head = head.next;
slow = slow.next;
}
return true;
}
private ListNode reverse(ListNode head) {
ListNode pre = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}