You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

有序链表(Sorted LinkedList)元素添加方法实现咨询

实现有序链表的升序插入方法

嘿,我来帮你完善这个SortedList的add方法,确保每次插入整数都能维持链表的升序状态。咱们一步步拆解逻辑,再给出完整实现:

核心思路

要实现升序插入,得覆盖几种典型场景:

  • 链表为空时,直接把新节点作为头节点
  • 新节点的值比头节点还小,直接插在链表最前面
  • 其他情况,遍历链表找到第一个比新节点值大的节点,把新节点插在它前面
  • 每次插入后别忘了更新listCount计数器

完整的add方法实现

public void add(int num) {
    Node newNode = new Node(num);
    // 场景1:链表为空,直接将新节点设为头节点
    if (head == null) {
        head = newNode;
        listCount++;
        return;
    }
    // 场景2:新节点值小于头节点,插在链表头部
    if (num < head.value) {
        newNode.next = head;
        head = newNode;
        listCount++;
        return;
    }
    // 场景3:遍历链表找插入位置,需要跟踪前驱节点
    Node prev = head;
    Node current = head.next;
    // 循环找到第一个值大于num的节点,此时prev就是它的前驱
    while (current != null && current.value <= num) {
        prev = current;
        current = current.next;
    }
    // 将新节点插入到prev和current之间
    prev.next = newNode;
    newNode.next = current;
    listCount++;
}

关键细节说明

  • 前驱节点跟踪:用prev指针跟着current移动,这样找到插入位置时,能直接通过prev把新节点链入,不用回头查找前驱,效率更高
  • 循环边界:current != null避免空指针异常,current.value <= num保证我们停在第一个比新值大的节点前,确保插入后链表依然有序
  • 全场景覆盖:不管是插在头部、中间还是尾部(当current为null时就是尾部),这段逻辑都能完美处理

这样实现后,每次调用add方法,整数都会被插入到正确的位置,链表始终保持升序状态~

内容的提问来源于stack exchange,提问作者Marina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:03:48