You need to enable JavaScript to run this app. 单链表insertAfterSecondOccurrence方法插入丢失尾节点问题求助
优惠活动
大模型
产品
解决方案
定价
更多

单链表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 ]

问题分析

  1. 核心错误在插入逻辑:原代码最后三行pred.next = pred是将节点的next指向自身,形成循环引用,之后p3.next = tmp直接覆盖了p3原本的next节点,导致原p3.next及之后的所有节点丢失(比如示例中的9)。
  2. 查找逻辑冗余:没必要先遍历统计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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:31:07