1

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

1 Answer 1

2

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
}

Sign up to request clarification or add additional context in comments.

2 Comments

That solution work perfectly but is it possible to do it without return the node? Can L.head be passed by refrence? I thought it was, given that it's a pointer.
You can pass &L.head, and set the head in the function using *node=&Node{}. It is a little harder to look at, but it will work. When you pass a pointer to a function, that function sets the value pointed to by that pointer. If you want to set L.head you have to send &L.head, not L.head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.