The root of the issue is that calling head.insertAtBegining(30)
does not change the value of head (it still points at the node{42, nil}
).
You have developed this on the asumption that the n = nn
in insertAtBegining
will update head
but that is not the case. I think it's easier to understand if insertAtBegining
is a standard function rather than a method:
insertAtBegining(head, 30)
...
func insertAtBegining(n *node, d int) *node{
nn := &node{d,n}
n = nn
}
As Go passes all parameters by value (you can pass a pointer but that is passed as a value) I think it's clear that this would not change head
(if you wanted to do that you would need to define the function func insertAtBegining(n **node, d int) *node{
and pass it &head
.
The issue is the same in your method.
The simplest fix for this is to redefine insertAtBegining
as (playground):
func (n *node) insertAtBegining(d int) *node{
nn := &node{d,n}
return nn
}
It now returns the new head so you use it like: head = head.insertAtBegining(30)
.
Another approach is to encapuslate the list management within a struct; this is the approach taken in list.List. Doing this has the advantage that the user needs no understanding of how the list is stored.