Internally, list package implements doubly linked list.
How to import list package in go golang:
import "container/list"
Example:
package main
import (
"container/list"
"fmt"
)
func main() {
// Create a new list and insert elements in it.
l := list.New()
l.PushBack(1) // 1
l.PushBack(2) // 1 -> 2
l.PushFront(3) // 3 -> 1 -> 2
l.PushBack(4) // 3 -> 1 -> 2 -> 4
// Iterate through list and print its elements.
for ele := l.Front(); ele != nil; ele = ele.Next() {
fmt.Println(ele.Value)
}
}
Output:
3
1
2
4
There are two structures used in list package.
- Element structure
- List structure
“Element” structure in list package
Here, Element is an element of a linked list.
type Element struct {
// next and prev are pointers of doubly-linked list.
next, prev *Element
// The list to which this element belongs.
list *List
// The value stored with this element.
Value interface{}
}
“List” structure in list package
List represents a doubly linked list. The zero value for List is an empty list and it is ready to use.
type List struct {
// contains filtered or unexported fields
}
list package has following given below set of functions to perform operation on linked list.
Functions under “Element” structure:
Functions under “List” structure:
To learn more about golang, Please refer given below link.
https://techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
https://golang.org/pkg/container/list/