Palindrome Linked List
思路:
Java code:
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) return true;
if (head.next == null) return true;
if (head.next.next == null) return head.val == head.next.val;
ListNode slow = head;
ListNode fast = head;
int halfLength = 0;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
halfLength++;
}
// 检查node个数奇偶,如果恰好fast在最右边,则是奇数,此时slow在正中间,则
// halfLength --,否则的话需要手动把fast右移一位。
if (fast.next == null) {
halfLength--;
} else {
fast = fast.next;
}
ListNode right = reverse(slow.next); // reverse之后从两头比较。
for (int i = 0; i < halfLength + 1; ++i) {
if (right.val != head.val) return false;
right = right.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode node) {
if (node == null || node.next == null) return node;
ListNode prev = null;
ListNode curr = node;
ListNode next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}