我是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/