LeetCode设计链表代码Bug排查:删除操作异常求助
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:
addAtHead(1)→ List:1, size=1addAtTail(3)→ List:1->3, size=2addAtIndex(1,2)→ List:1->2->3, size=3get(1)returns 2 (correct)deleteAtIndex(1)→ List:1->3, size=2get(1)returns 3 (matches expected output)
内容的提问来源于stack exchange,提问作者Aleksandr T

