Golang : Linked list example
In Golang, I would say that slices superseded list.... as slices would allow you to dynamically resize, pop, push, cut, delete and copy. However, if you still want to use list for LIFO-FIFO stuff... you can use the container/list
package.
Here is a linked list example in Golang.
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
// list elements
for e := alist.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value.(string))
}
// pop 3 elements
alist.Remove(alist.Front())
alist.Remove(alist.Front())
alist.Remove(alist.Front())
fmt.Println("Size after remove(pop) : ", alist.Len()) // list size after
}
Output :
Size before : 0
Size after insert(push): 3
a
b
c
Size after remove(pop) : 0
References :
https://www.socketloop.com/references/golang-container-list-new-function-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
+10.3k Golang : Get local time and equivalent time in different time zone
+13.3k Golang : Activate web camera and broadcast out base64 encoded images
+7.5k Golang : Trim everything onward after a word
+7.5k Golang : get the current working directory of a running program
+20.3k Golang : Read directory content with os.Open
+16.2k Golang : Delete files by extension
+21.6k Golang : Join arrays or slices example
+9.1k Golang : Scramble and unscramble text message by randomly replacing words
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+13.1k Golang : Generate Code128 barcode
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+29.4k Golang : Get time.Duration in year, month, week or day