add a node to the beginning of a linked list in go

To add a node to the beginning of a linked list in Go, we need to create a new node and point the head of the linked list to the new node. The following code snippet demonstrates how to add a node to the beginning of a linked list in Go:

main.go
type Node struct {
    value int
    next  *Node
}

func addNode(head **Node, value int) {
    newNode := &Node{
        value: value,
        next:  *head,
    }
    *head = newNode
}
185 chars
13 lines

In the code above, we define a Node struct and a function called addNode which takes a pointer to the head of the linked list and a value to insert.

Inside the addNode function, we first create a new node with the specified value and set its next pointer to the current head of the linked list. We then set the head of the linked list to the new node, effectively making the new node the new head of the list.

To use this function, we can create a new linked list with a head pointer of nil and add nodes to it like this:

main.go
func main() {
    var head *Node
    
    addNode(&head, 3)
    addNode(&head, 2)
    addNode(&head, 1)
}
106 chars
8 lines

In the code above, we create a new linked list with a head pointer of nil, and then add three nodes to the beginning of the list, with values 1, 2, and 3. The resulting linked list will have a head node with a value of 1, followed by a node with a value of 2, and then a node with a value of 3.

gistlibby LogSnag