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
+31.1k Golang : Interpolating or substituting variables in string examples
+27k Golang : Convert file content into array of bytes
+13.8k Golang : Query string with space symbol %20 in between
+15.8k Golang : Force download file example
+10.5k Golang : Convert file unix timestamp to UTC time example
+7k Golang : Pat multiplexer routing example
+15.5k Golang : Accurate and reliable decimal calculations
+8.3k Golang : Variadic function arguments sanity check example
+9.4k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+6.4k Apt-get to install and uninstall Golang
+14.9k Golang : Normalize unicode strings for comparison purpose
+6.1k Facebook : How to force facebook to scrape latest URL link data?