思路:
为了达到O(N)的时间复杂度和O(1)的空间复杂度,分成三步完成。
1.利用快慢指针找到中间节点
2.从中间节点到尾部反转链表
3.从头和尾向中间遍历,判断是否相等
public boolean isPalindrome(ListNode head) {
if(head==null)return true;
ListNode mid = findMiddle(head);
ListNode last = reverse(mid);
boolean isPalindrome = true;
while (head != null) {
if (head.val != last.val) isPalindrome = false;
head=head.next;
last=last.next;
}
return isPalindrome;
}
public ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null) {
if (fast.next.next == null) break;
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverse(ListNode head) {
ListNode pre = head;
ListNode current = head.next;
while (current != null) {
ListNode next = current.next;
current.next = pre;
pre = current;
current = next;
}
head.next = null;
return pre;
}
本文介绍了一种链表回文检测算法,该算法通过快慢指针找到链表中间节点,然后反转后半部分链表,最后从两端向中间遍历比较节点值,判断链表是否为回文。

被折叠的 条评论
为什么被折叠?



