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
+13.7k Golang : Get all local users and print out their home directory, description and group id
+4.3k Javascript : Change page title to get viewer attention
+18.1k Golang : How to run your code only once with sync.Once object
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+6.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+8.4k Golang : ffmpeg with os/exec.Command() returns non-zero status
+3.7k Mac OSX : Get disk partitions' size, type and name
+6.5k Golang : Handling Yes No Quit query input
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+9.8k Golang : Generate random elements without repetition or duplicate
+7.6k Golang : Convert(cast) []byte to io.Reader type
+9.2k Golang : How to profile or log time spend on execution?