How to create a linked list in Go using the container/list package?

To create a linked list in Go using the container/list package, you can follow these steps:

  1. Import the container/list package into your Go program:
import ( "container/list" )
  1. Create a new instance of a linked list:
linkedList := list.New()
  1. Add elements to the linked list using the PushBack() method:
linkedList.PushBack("Element 1") linkedList.PushBack("Element 2") linkedList.PushBack("Element 3")
  1. Iterate over the elements of the linked list using the Front() method to get the first element, and the Next() method to get subsequent elements:
for element := linkedList.Front(); element != nil; element = element.Next() { fmt.Println(element.Value) }

This will print out:

Element 1 Element 2 Element 3

You can also use the PushFront() method to add elements at the front of the linked list, and the Remove() method to remove elements from the linked list.

Note: The Value field of each element in the linked list is of type interface{}, so you can store any type of value in the linked list.

Here's the complete code example:

package main import ( "container/list" "fmt" ) func main() { linkedList := list.New() linkedList.PushBack("Element 1") linkedList.PushBack("Element 2") linkedList.PushBack("Element 3") for element := linkedList.Front(); element != nil; element = element.Next() { fmt.Println(element.Value) } }