Java 链表回文判断:高效算法实现与代码解析
要判断一个链表是否为回文链表,可以使用快慢指针和栈的方法。
首先,使用快慢指针找到链表的中间节点。快指针每次移动两步,慢指针每次移动一步,当快指针到达链表末尾时,慢指针刚好到达链表的中间节点。
然后,将慢指针后面的节点依次入栈。
最后,再次使用快慢指针从链表的头部和中间节点开始遍历比较节点的值是否相等。如果有不相等的节点,说明链表不是回文链表;如果全部节点都相等,说明链表是回文链表。
下面是 Java 代码实现:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
Stack<Integer> stack = new Stack<>();
while (fast != null && fast.next != null) {
stack.push(slow.val);
slow = slow.next;
fast = fast.next.next;
}
// 处理链表长度为奇数的情况
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (slow.val != stack.pop()) {
return false;
}
slow = slow.next;
}
return true;
}
这段代码的时间复杂度为 O(n),其中 n 是链表的长度。
原文地址: https://www.cveoy.top/t/topic/cQ2N 著作权归作者所有。请勿转载和采集!