Reputation: 91
I'm trying to create a linear linked list in go with recursive functions but for some reason I am not getting the correct result.
When I add a number to the list I noticed that L.head
is never updated after the return of the recursiveAdd
method. Shouldn't it be updated given that it is a pointer?
Expected result after list.Display()
:
1
2
3
Actual result: empty string
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()
}
Upvotes: 1
Views: 533
Reputation: 51587
List.Add
does not update L.head
. You pass L.head
to recursiveAdd
, but what you're passing is a copy of L.head
, which is nil, and when you assign a value to that you only update the copy of the pointer on stack, not L.head
. You can do:
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
}
Upvotes: 2