Golang : Iterate linked list example
Alright, you have created a linked list with container/list
and now you wonder how are you going to iterate over the elements inside the linked list.
Below is a code fragment from my previous example on how to create a linked list with Go. To iterate over the list elements, use a for loop until all the elements in the list are exhausted. To get the first element, use Front()
method and next element with Next()
method.
Here you go!
package main
import (
"container/list"
"fmt"
)
func main() {
// create a new link list
alist := list.New()
fmt.Println("Size before : ", alist.Len()) // list size before
// push element into list
alist.PushBack("a")
alist.PushBack("b")
alist.PushBack("c")
fmt.Println("Size after insert(push): ", alist.Len()) // list size after
// iterate over list elements
for e := alist.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value.(string))
}
}
You play this code at http://play.golang.org/p/WGcldjJavQ
Output :
Size before : 0
Size after insert(push): 3
a
b
c
See also : Golang : Linked list example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.8k Golang : GORM create record or insert new record into database example
+8k Random number generation with crypto/rand in Go
+23k Golang : Time slice or date sort and reverse sort example
+4.7k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+10.2k Golang : flag provided but not defined error
+9.5k Golang : Bubble sort example
+5.8k Golang : Takes a plural word and makes it singular
+10.3k Golang : Secure file deletion with wipe example
+9.5k Golang : Get currencies exchange rates example
+14.6k Golang : Read a file line by line
+11.9k Golang : Get user input until a command or receive a word to stop
+7.9k Golang : Serving HTTP and Websocket from different ports in a program example