remove a node from the end of a linked list in go

To remove the last node of a linked list in Go, we need to traverse the entire list to reach the second-to-last node, and then update its next pointer to nil. Here's an example implementation:

main.go
type Node struct {
    data interface{}
    next *Node
}

func removeFromEnd(head *Node) *Node {
    if head == nil || head.next == nil {
        return nil // empty or single-node list
    }
    curr := head
    for curr.next.next != nil {
        curr = curr.next
    }
    curr.next = nil
    return head
}
310 chars
17 lines

Here, we first handle the case where the list is empty or has only one node. If there are more than one nodes, we start traversing the list from the head until we reach the penultimate node (i.e., the node whose next field points to the last node). Then, we update the next pointer of the penultimate node to nil, effectively removing the last node from the list. Finally, we return the head of the updated list.

gistlibby LogSnag