To create a linked list in Go using the container/list
package, you can follow these steps:
container/list
package into your Go program:import (
"container/list"
)
linkedList := list.New()
PushBack()
method:linkedList.PushBack("Element 1")
linkedList.PushBack("Element 2")
linkedList.PushBack("Element 3")
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)
}
}