Go 中的 For 循环无限运行,同时将节点添加到链表

问题描述 投票:0回答:1

我是Golang新手,正在尝试实现其中的一些数据结构和算法,

我写了一个go函数,将数据添加到列表中,但由于某种原因,它进入了无限循环,我已经尝试了各种方法都无济于事,最后我还在互联网上搜索了链接列表的实际代码并找到了各种实现,但它们都卡在同一个地方,

我的代码
// linked-list.go

type Node struct {
    data int
    next *Node
}

type LinkedList struct {
    head *Node
}

func (ll *LinkedList) Add(value int) {
    node := &Node{
        data: value,
    }
    if ll.head == nil {
        ll.head = node
    }

    curr := ll.head
    for curr.next != nil {  // this is where the code gets stuck
        curr = curr.next    // this is not pointing it to the next node
    }

    curr.next = node
}
// main.go

func main() {
    ll := modules.LinkedList{}
    ll.Print()
    ll.Add(1)
    ll.Add(2)
    ll.Print()
}

我从网上尝试过的一些代码

供参考:

golang 程序
中型博客

go data-structures linked-list
1个回答
0
投票

return
在 if 条件下当
ll.head == nil
时。当前函数的最后一行正在将
head
指定为
head.next
,从而形成一个永远不会结束的循环链表。

© www.soinside.com 2019 - 2024. All rights reserved.