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

To add a node to the end of a linked list in Go, we can follow the below algorithm:

  1. Create a new node with the provided value.
  2. If the linked list is empty, make the new node the head of the list.
  3. Traverse through the list until we reach the last node.
  4. Set the next pointer of the last node to point to the new node.

Here's the implementation of the algorithm:

main.go
package main

import "fmt"

type Node struct {
    value int
    next  *Node
}

func addAtEnd(head *Node, value int) *Node {
    newNode := &Node{value: value}

    // if linked list is empty, make the new node as head node
    if head == nil {
        head = newNode
        return head
    }

    // traverse through the linked list until we reach the last node
    last := head
    for last.next != nil {
        last = last.next
    }

    // set the next pointer of the last node to the new node
    last.next = newNode
    return head
}

func main() {
    // create a sample linked list
    head := &Node{value: 1}
    head.next = &Node{value: 2}
    head.next.next = &Node{value: 3}

    // add a node to the end of the linked list
    head = addAtEnd(head, 4)

    // print linked list
    for head != nil {
        fmt.Printf("%d -> ", head.value)
        head = head.next
    }
}
890 chars
45 lines

In the above code, we first create a new node using the provided value. If the linked list is empty, we make the new node the head of the list. Otherwise, we traverse through the list until we reach the last node and set its next pointer to point to the new node. Finally, we return the head of the linked list with the new node added.

gistlibby LogSnag