循环链表插入位置0时head未更新引发无限循环问题排查
循环链表插入头部引发无限循环的原因与修复
问题根源
你在insertAtPos方法插入位置0时,只更新了新节点的next和全局head指针,但循环链表的最后一个节点的next仍然指向旧的head,直接破坏了循环链表的闭环结构:
- 原本的循环链表是最后一个节点指向旧
head,形成完整闭环; - 插入新节点到头部后,新
head指向旧head,但最后一个节点仍指向旧head,导致遍历到最后一个节点时,会跳回旧head进入循环,永远无法回到新head,最终引发无限循环。
对比你的insertAtEnd方法,它正确处理了闭环维护:找到最后一个节点(current.next == head的节点),将其next设为新节点,同时新节点next指向head,确保整个链表始终是一个完整的环。
修复方案
修改insertAtPos方法中position == 0的分支,分两种情况处理并维护闭环:
public void insertAtPos(Card data, int position) { if (position < 0) { System.out.println("Invalid position. Position cannot be negative"); return; } Node newNode = new Node(data); if (position == 0) { if (head == null) { // 空链表时,新节点自闭环 newNode.next = newNode; head = newNode; } else { newNode.next = head; // 找到最后一个节点 Node current = head; do { current = current.next; } while (current.next != head); // 让最后一个节点指向新的head,维持闭环 current.next = newNode; head = newNode; } } else { Node current = head; int currentIndex = 0; // 循环链表中current不会为null,改为判断是否到达目标位置且未回到head(避免越界循环) while (currentIndex < position - 1 && current.next != head) { current = current.next; currentIndex++; } if (currentIndex != position - 1) { System.out.println("Position is out of bounds"); return; } newNode.next = current.next; current.next = newNode; } }
额外说明
原else分支中的current != null判断无意义(循环链表不存在null节点),改为current.next != head可以避免当position超过链表长度时,出现无限循环遍历的问题。
内容的提问来源于stack exchange,提问作者righN
相关产品推荐
相关产品推荐

