Given a singly linked list, determine if it is a palindrome.
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
class Solution {
public ListNode reverseList(ListNode A) {
ListNode prev = null, current = A;
while (current.next != null) {
ListNode temp = current.next;
current.next = prev;
prev = current;
current = temp;
}
current.next = prev;
return current;
}
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null)
return true;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
if (fast.next.next == null) {
break;
}
fast = fast.next.next;
slow = slow.next;
}
ListNode right = slow.next;
slow.next = null;
ListNode left = reverseList(head);
if (fast != slow && fast.next == null)
left = left.next;
while (left != null && right != null) {
if (left.val != right.val)
return false;
left = left.next;
right = right.next;
}
return true;
}
}