直接做的话每次要找到最后一个,再和一开始的比较,看起来很蠢,实际上也就是挺蠢的。
先快慢指针找到一半,把后半部分reverse,然后两个部分从头开始比较。。
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode head1 = new ListNode(0);
head1.next = head;
ListNode slow = head1;
ListNode fast = head1;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head2 = new ListNode(0);
head2.next = slow.next;
slow.next = null;
// reverse 2nd half
ListNode prev = null;
ListNode temp = head2.next;
ListNode next = temp.next;
while (next != null) {
temp.next = prev;
prev = temp;
temp = next;
next = next.next;
}
temp.next = prev;
// compare
ListNode curr = head;
while (temp != null && curr != null) {
if (temp.val != curr.val) return false;
temp = temp.next;
curr = curr.next;
}
return true;
//1 2 3 4
// 1 2 3 4 5
}
}