Java按位置删除链表节点时delete方法无效果,求错误排查
代码问题分析
- 头节点删除逻辑错误:当position为0要删除头节点时,你仅修改了临时变量
current的指向,没有真正修改链表的head属性。临时变量current只是保存了头节点的地址副本,修改它不会改变原链表的头节点指向,正确操作应该是直接赋值l.head = l.head.next。 - 非头节点删除逻辑错误:遍历找到待删除节点的前置节点后,你写的
current = current.next.next还是只修改了临时变量current的指向,没有修改前置节点的next引用。只有修改current.next = current.next.next,才能让前置节点直接跳过待删除节点,指向后面的节点,真正完成删除操作。 - 缺失边界校验:代码没有判断空链表、position为负数、position大于等于链表长度的场景,很容易触发空指针异常。
修正后的delete方法代码
public LinkedList delete(LinkedList l, int position) { // 边界校验 if (l.head == null || position < 0) { return l; } // 处理头节点删除场景 if (position == 0) { l.head = l.head.next; // 输出修改后的链表 Node iterating = l.head; while(iterating != null){ System.out.print(iterating.data + " "); iterating = iterating.next; } return l; } Node current = l.head; int index = 0; // 遍历到待删除节点的前一个节点 while (current != null && index < position - 1) { current = current.next; index++; } // 校验position是否超出链表长度 if (current == null || current.next == null) { return l; } // 修改节点next引用完成删除 current.next = current.next.next; // 输出修改后的链表 Node iterating = l.head; while(iterating != null){ System.out.print(iterating.data + " "); iterating = iterating.next; } return l; }
内容的提问来源于stack exchange,提问作者sailesh kumar
相关产品推荐
相关产品推荐

