Last active
March 15, 2020 20:52
-
-
Save halkyon/89e78420e558e966e1f03b258d889fc7 to your computer and use it in GitHub Desktop.
Simple example of a circular doubly linked list in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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