Pointers Golang指针作为nil传递给方法时未更新
我试图用递归函数创建一个线性链表,但由于某些原因,我没有得到正确的结果 当我向列表中添加一个数字时,我注意到Pointers Golang指针作为nil传递给方法时未更新,pointers,go,recursion,Pointers,Go,Recursion,我试图用递归函数创建一个线性链表,但由于某些原因,我没有得到正确的结果 当我向列表中添加一个数字时,我注意到L.head在返回recursiveAdd方法后从未更新。如果它是指针,不应该更新吗 list.Display()之后的预期结果 1. 2. 三, 实际结果:空字符串 package main import "fmt" type Node struct { num int next *Node } type List struct { head *Node }
L.head
在返回recursiveAdd
方法后从未更新。如果它是指针,不应该更新吗
list.Display()之后的预期结果
1.
2.
三,
实际结果:空字符串
package main
import "fmt"
type Node struct {
num int
next *Node
}
type List struct {
head *Node
}
func (L *List) Add(n int) {
L.recursiveAdd(L.head, n)
}
func recursiveAdd(node *Node, n int){
if node == nil {
node = &Node{n, nil}
return
}
L.recursiveAdd(node.next, n)
}
func (L *List) Display() {
recursiveDisplay(L.head)
}
func recursiveDisplay(n *Node){
if n == nil {
return
}
fmt.Println(n.num)
recursiveDisplay(n.next)
}
func main(){
list := List{}
list.Add(1)
list.Add(2)
list.Add(3)
list.Display()
}
List.Add
不更新L.head
。您将L.head
传递给recursiveAdd
,但传递的是L.head
的副本,该副本为零,当您为该值赋值时,您只更新堆栈上指针的副本,而不是L.head
。你可以做:
func (L *List) Add(n int) {
l.head=L.recursiveAdd(L.head, n)
}
func (L *list) recursiveAdd(node *Node, n int) *Node{
if node == nil {
node = &Node{n, nil}
return node
}
node.next=L.recursiveAdd(node.next,n)
return node
}
该解决方案工作得很好,但是否可以不返回节点就执行该解决方案?L.head
可以通过引用传递吗?如果它是一个指针,我想是的。您可以传递&L.head
,并使用*node=&node{}
在函数中设置head。这是一个有点难看,但它会工作。将指针传递给函数时,该函数将设置该指针指向的值。如果要设置L.head
,则必须发送&L.head
,而不是L.head
。