Skip to content

Instantly share code, notes, and snippets.

@halkyon
Last active March 15, 2020 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halkyon/89e78420e558e966e1f03b258d889fc7 to your computer and use it in GitHub Desktop.
Save halkyon/89e78420e558e966e1f03b258d889fc7 to your computer and use it in GitHub Desktop.
Simple example of a circular doubly linked list in Go
package main
import (
"fmt"
)
type list struct {
head *item
tail *item
}
type item struct {
name string
prev *item
next *item
}
func main() {
list := &list{}
list.add(&item{name: "foo"})
list.add(&item{name: "bar"})
list.add(&item{name: "baz"})
list.show()
}
func (list *list) add(item *item) {
if list.head == nil {
list.head = item
} else {
currentItem := list.tail
currentItem.next = item
item.prev = list.tail
item.next = list.head
list.head.prev = item
}
list.tail = item
}
func (list *list) show() {
currentItem := list.head
if currentItem == nil {
return
}
fmt.Printf("%+v\n", currentItem)
for currentItem.next != nil {
currentItem = currentItem.next
if currentItem == list.head {
break
}
fmt.Printf("%+v\n", currentItem)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment