go - 使用Go创建链接列表

标签 go

我是golang和探索语言的新手。
我正在创建一个链表,但是它似乎超出范围并且不能正确存储变量。

当我使用此代码打印列表时,如果需要aa,bb,它将打印空白。

package main

import "fmt"

type Node struct {
    data string
    nextNode *Node
}

type MyLinkedList struct {
    head *Node
}


func (ll MyLinkedList) pushFront(data string) *Node {
    node := Node{data, nil}
    if ll.head == nil {
        ll.head = &node
        return ll.head
    }
    node.nextNode = ll.head
    ll.head = &node
    return ll.head
}

func print(ll MyLinkedList) {
    currentNode := ll.head
    for currentNode != nil {
        fmt.Print(currentNode.data + " ")
        currentNode = currentNode.nextNode
    }
}

func main() {
    var m = MyLinkedList{}
    m.pushFront("aa")
    m.pushFront("bb")
    print(m)
}

最佳答案

我修改了您的代码以使其正常工作。

import "fmt"

type Node struct {
    data string
    nextNode *Node
}

type MyLinkedList struct {
    head *Node
}


func (ll *MyLinkedList) pushFront(data string) {
    node := &Node{data, nil}
    if ll.head == nil {
        ll.head = node 
return
    }
    node.nextNode = ll.head
    ll.head = node 
}

func print(ll *MyLinkedList) {
    currentNode := ll.head
    for currentNode != nil {
        fmt.Print(currentNode.data + " ")
        currentNode = currentNode.nextNode
    }
}

func main() {
    var m = &MyLinkedList{}
    m.pushFront("aa")
    m.pushFront("bb")
    print(m)
}

因此,在您的代码中,您只需按值传递结构

要在运行时修改结构,通常使用结构指针
(Golang: I have a map of structs. Why can't I directly modify a field in a struct value?)

关于go - 使用Go创建链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005835/

相关文章:

string - Go:将 rune (字符串)转换为二进制的字符串表示形式

Go:提供静态模板

go - 如何下载fabric-sdk-go的所有依赖?

Go 中的 TCP 连接

dns - Go中从IP地址获取域名

c++ - 当对字段使用不同的值时,Protobuf 序列化长度不同

unit-testing - 我如何在 Go 中编写使用 -short 标志的测试,它可以与 -benchmark 标志结合使用吗?

json - 编码 time.Time 到 unix 时间戳

go - 如何在 Golang 中打印接口(interface)的单个​​元素值

postgresql - 如何插入 slice