I want to remove a Node from a linked list in Go, and I have this struct and these methods:

type Node struct {
    Next *Node
    Val  int
}

func (n *Node) Append(val int) {
    end := &Node{Val: val}
    here := n
    for here.Next != nil {
        here = here.Next
    }
    here.Next = end
}

func Remove(n *Node, val int) *Node {
    head := n
    for head.Next != nil {
        if head.Next.Val == val {
            head.Next = head.Next.Next
            return head
        }
        head = head.Next
    }
    return head
}

func NewNode(val int) *Node {
    return &Node{Val: val}
}

I want to remove an item like this:


n := NewNode(1)
n.Append(2)
n.Append(3)
n.Append(4)
n.Append(5)

m := Remove(n, 3)

for m != nil {
    fmt.Println(n.Val)
    m = m.Next
}

The items that get printed out are 3 and 5, not 1,2,4and5`. I re-implemented this code in Python and got the expected answer. What is going on in Go? I have a feeling it has to do something with pointers.

1 Answers

1
Community On

You lose the head from returning a node you use to traverse. Also you are printing out the wrong object

type Node struct {
    Next *Node
    Val  int
}

func (n *Node) Append(val int) {
    end := &Node{Val: val}
    here := n
    for here.Next != nil {
        here = here.Next
    }
    here.Next = end
}

func Remove(n *Node, val int) *Node {
    traverser := n
    for traverser.Next != nil {
        if traverser.Next.Val == val {
            traverser.Next = traverser.Next.Next
            return n
        }
        traverser = traverser.Next
    }
    return n
}

func NewNode(val int) *Node {
    return &Node{Val: val}
}

func main() {
    n := NewNode(1)
    n.Append(2)
    n.Append(3)
    n.Append(4)
    n.Append(5)

    m := Remove(n, 3)

    for m != nil {
        fmt.Println(m.Val)
        m = m.Next
    }
}