Implement a function to check if a linked list is a palindrome.
分析:用快慢指针找到中点。中点以后倒序排列。然后head和mid两个指针进行比较即可。
注意快慢指针条件
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode fast = head.next, slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode head2 = slow.next;
ListNode curr = null;
if(head2 != null) {
curr = head2.next;
head2.next = null;
}
while(head2 != null && curr != null) {
ListNode tmp = curr.next;
curr.next = head2;
head2 = curr;
curr = tmp;
}
slow.next = head2;
while(slow.next != null && slow.next.val == head.val) {
slow = slow.next;
head = head.next;
}
return slow.next == null;
}
}