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

LeetCode设计链表代码Bug排查:删除操作异常求助

Bug Analysis & Fix for Design Linked List Implementation

The core issue causing your test case failure lies in the addAtIndex function: when inserting a new node, you're not linking it to the subsequent node in the list, which breaks the chain and loses the tail portion of the list.

Root Cause

In your current addAtIndex implementation, after creating the new node, you directly set iter?.next = new but never assign new.next to the original iter?.next. This means the new node's next remains null, cutting off the rest of the list. For your test case, inserting 2 at index 1 breaks the link between 1 and 3, so after insertion, the list becomes 1 -> 2 instead of 1 -> 2 -> 3. When you later delete index 1, the list is just 1, and trying to get index 1 (which is out of bounds for size 1) returns -1.

Fixed Code for addAtIndex

fun addAtIndex(index: Int, `val`: Int) {
    if (index > size)
        return

    if (index == 0) {
        addAtHead(`val`)
        return
    }
    
    var iter = head
    for (i in 0 until index - 1) {
        iter = iter?.next
    }
    val new = ListNode(`val`)
    // Fix: Link new node to the next node before updating iter's next
    new.next = iter?.next
    iter?.next = new
    size++
}

Additional Minor Bug Fix (addAtTail for Empty List)

Your addAtTail function doesn't handle the case when the list is empty (size=0). Adding this check ensures proper behavior:

fun addAtTail(`val`: Int) {
    if (size == 0) {
        addAtHead(`val`)
        return
    }
    var iter = head
    for (i in 0 until size - 1) {
        iter = iter?.next
    }
    
    val new = ListNode(`val`)
    iter?.next = new
    size++
}

Verification with Your Test Case

After applying the fix:

  1. addAtHead(1) → List: 1, size=1
  2. addAtTail(3) → List: 1->3, size=2
  3. addAtIndex(1,2) → List: 1->2->3, size=3
  4. get(1) returns 2 (correct)
  5. deleteAtIndex(1) → List: 1->3, size=2
  6. get(1) returns 3 (matches expected output)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:35:38