单链表insertAfterSecondOccurrence方法插入丢失尾节点问题求助
链表插入方法问题排查与修复
问题说明
实现了方法public void insertAfterSecondOccurrence(T e1, T e2),需求是在第二个出现的元素e2之后插入元素e1,但存在bug:当插入位置在链表最后一个元素之前时,会丢失原尾节点,而非将元素追加到链表中。
现有代码
public void insertAfterSecondOccurrence(T e1, T e2) { // insert e1 after the second occurence of e2 if(isEmpty()) { System.out.println("Error the list is empty."); } SLLNode<T> p = head; int count = 0; for(int i = 0; i < size(); i++) { if(p.info.equals(e2)) { count++; } p = p.next; } if(count <= 1) { System.out.println("Error there is no sec"); } SLLNode<T> p2 = head; SLLNode<T> p3 = head; SLLNode<T> pred =head; SLLNode<T> tmp = new SLLNode<T>(e1); int count2 = 0; for(int i = 0; i < size(); i++) { if(p2.info.equals(e2)) { pred = p2.next; p3 = p2; count2++; } if(count2 == 2) { break; } p2 = p2.next; } pred.next = pred; pred = pred.next; p3.next = tmp; }
尝试过的修改
曾将最后三行替换为以下代码,但未解决问题:
tail.next = tail; tail = tail.next; p3.next = tmp;
示例情况
- 原链表:
[ 7 5 3 50 7 9 ] - 调用方法(插入
30在第二个7之后)预期结果:[ 7 5 3 50 7 30 9 ] - 实际结果:
[ 7 5 3 50 7 30 ]
问题分析
- 核心错误在插入逻辑:原代码最后三行
pred.next = pred是将节点的next指向自身,形成循环引用,之后p3.next = tmp直接覆盖了p3原本的next节点,导致原p3.next及之后的所有节点丢失(比如示例中的9)。 - 查找逻辑冗余:没必要先遍历统计
e2出现次数,再遍历找第二个e2,可以合并为一次遍历;另外pred变量的赋值逻辑混乱,完全没起到作用。
修复方案
简化查找逻辑,修正插入步骤:
public void insertAfterSecondOccurrence(T e1, T e2) { if(isEmpty()) { System.out.println("Error the list is empty."); return; // 空列表直接返回,避免后续执行 } SLLNode<T> current = head; int count = 0; // 遍历找到第二个e2的节点 while (current != null) { if(current.info.equals(e2)) { count++; // 找到第二个e2时,执行插入 if(count == 2) { SLLNode<T> tmp = new SLLNode<>(e1); // 把tmp的next指向current原本的下一个节点 tmp.next = current.next; // 把current的next指向tmp,完成插入 current.next = tmp; // 如果插入的位置是最后一个节点之后,更新tail if(tmp.next == null) { tail = tmp; } return; // 插入完成后直接返回 } } current = current.next; } // 遍历结束没找到第二个e2,输出错误 System.out.println("Error there is no second occurrence of " + e2); }
修复要点
- 一次遍历完成查找与插入:无需先统计次数,找到第二个
e2时立即执行插入,提升效率。 - 正确的插入逻辑:通过
tmp.next = current.next保留原后续节点,再将current.next指向tmp,确保链表不丢失节点。 - 更新尾节点:如果插入后
tmp成为新的尾节点(即原current是尾节点),更新tail指针。 - 提前返回:空列表或找到目标后直接返回,避免无效代码执行。
内容的提问来源于stack exchange,提问作者AliAlrebdi
相关产品推荐
相关产品推荐

