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

Go语言链表添加节点时陷入无限循环问题求助

问题分析与修复

问题根源

你的Add函数存在两个核心问题,直接导致了无限循环:

  1. 当链表为空(head为nil)时,设置head = node后没有终止函数,后续代码继续执行。
  2. 后续代码会将当前节点的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:27:20