234. 回文链表
2019-12-30 本文已影响0人
Andysys
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head, fast = head.next, pre = null, ppre = null;
while (fast != null && fast.next != null) {
pre = slow;
// 后移
slow = slow.next;
fast = fast.next.next;
// 反向指针
pre.next = ppre;
ppre = pre;
}
ListNode p2 = slow.next;
slow.next = pre;
ListNode p1 = fast == null ? slow.next : slow;
while (p1 != null) {
if (p1.val != p2.val) {
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}