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()
}