Go语言链表添加节点时陷入无限循环问题求助
问题分析与修复
问题根源
你的Add函数存在两个核心问题,直接导致了无限循环:
- 当链表为空(
head为nil)时,设置head = node后没有终止函数,后续代码继续执行。 - 后续代码会将当前节点的
next指向新节点,使得第一个节点的next指向自身,形成自环。第二次调用Add时,遍历循环会因为这个环永远无法结束。
举个具体例子:
- 第一次调用
Add(1),head被设为新节点,随后执行curr.next = node,让这个节点的next指向自己,形成环。 - 第二次调用
Add(2),curr从head开始,curr.next != nil永远为真(因为指向自己),循环会一直执行curr = curr.next,陷入无限循环。
修复后的代码
方法一:在空链表分支添加return终止函数
func (ll *LinkedList) Add(value int) { node := &Node{ data: value, } if ll.head == nil { ll.head = node return // 终止函数,避免后续代码执行 } curr := ll.head for curr.next != nil { curr = curr.next } curr.next = node }
方法二:使用else分支分离空链表与非空链表逻辑
func (ll *LinkedList) Add(value int) { node := &Node{data: value} if ll.head == nil { ll.head = node } else { curr := ll.head for curr.next != nil { curr = curr.next } curr.next = node } }
内容的提问来源于stack exchange,提问作者Tr4cEr
相关产品推荐
相关产品推荐

