snippets:golang:containers:doublelist
double linked list
- snippet.go
package main
import "fmt"
// MyListElement contains custom-attributes and internal data
type MyListElement struct {
Name string
Age int
next *MyListElement
prev *MyListElement
}
// Next iterates to the next list element, or nil if end of list
func (i *MyListElement) Next() *MyListElement {
return i.next
}
// MyList structure, pointer for begin and end element
type MyList struct {
head *MyListElement
tail *MyListElement
}
// Append item to end of list
func (list *MyList) Append(item *MyListElement) {
if list.head == nil && list.tail == nil {
list.head = item
list.tail = item
item.next = nil
item.prev = nil
return
}
list.tail.next = item
item.prev = list.tail
item.next = nil
list.tail = item
}
func (list *MyList) Delete(item *MyListElement) {
if list.head == item && list.tail == item && item.prev == nil && item.next == nil {
list.head = nil
list.tail = nil
return
}
item.prev = item.next
item.next = item.prev
}
// Count elements in list
func (list *MyList) Count() int {
count := 0
for i := list.head; i != nil; i = i.next {
count++
}
return count
}
func main() {
list := MyList{}
{
a := &MyListElement{Name: "Max", Age: 23}
list.Append(a)
}
{
b := &MyListElement{Name: "Hans", Age: 42}
list.Append(b)
}
fmt.Println(list.Count())
}
snippets/golang/containers/doublelist.txt · Last modified: by allspark