How to remove elements from a linked list in Go?

To remove elements from a linked list in Go, you can follow these steps:

  1. Define a struct for the linked list node. It should have a value field to hold the data and a next field to point to the next node.
type Node struct { value interface{} next *Node }
  1. Define a struct for the linked list. It should have a head field to keep track of the first node.
type LinkedList struct { head *Node }
  1. Implement a function to remove an element from the linked list.
func (list *LinkedList) Remove(value interface{}) { if list.head == nil { return } // Handling case where the head node holds the value to be removed if list.head.value == value { list.head = list.head.next return } // Traverse the linked list to find the node holding the value prev := list.head current := list.head.next for current != nil { if current.value == value { prev.next = current.next return } prev = current current = current.next } }

Here's a complete example to illustrate the usage:

package main import ( "fmt" ) type Node struct { value interface{} next *Node } type LinkedList struct { head *Node } func (list *LinkedList) Remove(value interface{}) { if list.head == nil { return } // Handling case where the head node holds the value to be removed if list.head.value == value { list.head = list.head.next return } // Traverse the linked list to find the node holding the value prev := list.head current := list.head.next for current != nil { if current.value == value { prev.next = current.next return } prev = current current = current.next } } func (list *LinkedList) Print() { current := list.head for current != nil { fmt.Printf("%v ", current.value) current = current.next } fmt.Println() } func main() { list := LinkedList{} // Adding elements to the linked list list.head = &Node{value: 1} node1 := &Node{value: 2} node2 := &Node{value: 3} node3 := &Node{value: 4} list.head.next = node1 node1.next = node2 node2.next = node3 // Printing the original linked list fmt.Println("Original Linked List:") list.Print() // Removing element 3 from the linked list list.Remove(3) // Printing the modified linked list fmt.Println("Modified Linked List:") list.Print() }

The output will be:

Original Linked List: 1 2 3 4 Modified Linked List: 1 2 4

In this example, we create a linked list with elements 1, 2, 3, and 4. We then remove the element 3 from the list and print the modified list.