使用Go语言实现链表
时间:2024-02-22
浏览:383
作者:佚名
一分耕耘,一分收获!既然打开了这篇文章《使用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语言实现链表》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
