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
+7.1k Golang : Gorrila mux.Vars() function example
+8.7k Golang : Heap sort example
+17k Golang : Covert map/slice/array to JSON or XML format
+37.1k Golang : Converting a negative number to positive number
+17.8k Golang : Login and logout a user after password verification and redirect example
+9.6k Golang : Eroding and dilating image with OpenCV example
+6.3k Unix/Linux : Use netstat to find out IP addresses served by your website server
+8.5k Golang : Another camera capture GUI application with GTK and OpenCV
+11.5k Swift : Convert (cast) Float to String
+35.2k Golang : Strip slashes from string example
+12.2k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+29.9k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?