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

To remove a node from the middle of a linked list in Go, you can follow these steps:

  1. Create a function that accepts the linked list head and the value of the node to remove as parameters.
  2. Traverse the linked list to find the node with the given value.
  3. Once the node has been found, reassign the previous node's next pointer to the current node's next pointer.
  4. Remove the current node by setting its next pointer to nil.

Here is an example implementation:

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

func removeNode(head *Node, val int) *Node {
    // check if head node is the one to remove
    if head.value == val {
        return head.next
    }

    prev := head
    curr := head.next

    for curr != nil && curr.value != val {
        prev = curr
        curr = curr.next
    }

    if curr != nil {
        prev.next = curr.next
        curr.next = nil
    }

    return head
}
438 chars
27 lines

In this implementation, we first check if the head node is the one we want to remove. If it is, we simply return the next node as the new head.

Otherwise, we iterate through the linked list to find the node to remove. We keep track of the previous node as "prev" and the current node as "curr". Once we find the node to remove, we reassign "prev.next" to "curr.next" to skip over the current node. Finally, we set "curr.next" to nil to remove any references to the rest of the linked list.

This function returns the head of the modified linked list.

gistlibby LogSnag