链表回文判断代码问题:类双指针思路疑似存在疏漏,求排查
链表回文判断的类双指针实现问题
现有实现代码
public boolean palindromLinkedList() { //find size Node temp = head; int size=0; while(temp != null){ size++; temp=temp.next; } //find while loop iteration int c; if(size%2 ==0){ c = size/2; }else{ c = (size+1)/2; } //intialise start and end pointer Node start = head; Node end = tail; //index pointer int k =size-1; //loop for the palindrome condition while(c > 0){ // 原代码此处存在语法错误,需将反引号替换为左大括号 if(start.data != end.data){ return false; } start = start.next; Node find = head; k--; for(int i=0;i<=k;i++){ find = find.next; } end = find; c--; } return true; }
思路说明
我尝试用类双指针法判断链表是否为回文:
- 初始化两个指针:
start = head(从头部开始遍历)和end = tail(从尾部开始遍历) - 每次检查
start和end的节点数据是否相等,相等则将start后移一位,同时通过for循环从头遍历找到end的前一个节点 - 重复上述过程直到指针到达中间节点,若全程数据都相等则返回true,否则返回false
存在的问题及改进方向
- 语法错误:原代码中
while(c > 0)后面的反引号是笔误,必须替换为左大括号{才能正常编译 - 效率极低:每次找
end的前一个节点都要从head重新遍历,时间复杂度达到O(n²),长链表场景下性能很差 - 边界处理冗余:当链表长度为奇数时,
c = (size+1)/2的循环次数会让中间节点被重复检查,实际上只需要检查size/2次即可(奇数长度的中间节点不影响回文判断) - 依赖特定链表结构:代码依赖链表维护
tail指针,若链表没有这个属性,方法就无法直接使用,通用性不足
优化实现方案
可以通过反转链表后半段实现真正的高效双指针判断,时间复杂度O(n),空间复杂度O(1):
public boolean isPalindrome() { if (head == null || head.next == null) { return true; } // 找到链表中间节点 Node slow = head; Node fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 反转后半段链表 Node prev = null; Node curr = slow; while (curr != null) { Node nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } // 前后两段逐一比较 Node left = head; Node right = prev; while (right != null) { if (left.data != right.data) { return false; } left = left.next; right = right.next; } return true; }
内容的提问来源于stack exchange,提问作者Rishiksai Santhosh
相关产品推荐
相关产品推荐

