User Tools

Site Tools


snippets:golang:containers:singlelist

simple linked list

snippet.go
package main
 
import "fmt"
 
type MyListElement struct {
	Name string
	Age  int
 
	next *MyListElement
}
 
func (i *MyListElement) Next() *MyListElement {
	return i.next
}
 
type MyList struct {
	Head *MyListElement
}
 
func (list *MyList) Append(item *MyListElement) {
	if list.Head == nil {
		list.Head = item
		return
	}
 
	i := list.Head
	for ; i != nil && i.next != nil; i = i.next {
	}
	i.next = item
	item.next = nil
}
 
func (list *MyList) Count() int {
	count := 0
 
	for i := list.Head; i != nil; i = i.next {
		count += 1
	}
	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/singlelist.txt · Last modified: by allspark