This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| snippets:golang:containers:doublelist [2018/03/20 12:16] – created allspark | snippets:golang:containers:doublelist [2018/03/20 16:52] (current) – allspark | ||
|---|---|---|---|
| Line 6: | Line 6: | ||
| import " | import " | ||
| + | // MyListElement contains custom-attributes and internal data | ||
| type MyListElement struct { | type MyListElement struct { | ||
| Name string | Name string | ||
| Line 14: | Line 15: | ||
| } | } | ||
| + | // Next iterates to the next list element, or nil if end of list | ||
| func (i *MyListElement) Next() *MyListElement { | func (i *MyListElement) Next() *MyListElement { | ||
| return i.next | return i.next | ||
| } | } | ||
| + | // MyList structure, pointer for begin and end element | ||
| type MyList struct { | type MyList struct { | ||
| - | Head *MyListElement | + | head *MyListElement |
| - | Tail *MyListElement | + | tail *MyListElement |
| } | } | ||
| + | // Append item to end of list | ||
| func (list *MyList) Append(item *MyListElement) { | func (list *MyList) Append(item *MyListElement) { | ||
| - | if list.Head == nil { | + | if list.head == nil && list.tail |
| - | list.Head = item | + | list.head = item |
| - | list.Tail = item | + | list.tail = item |
| item.next = nil | item.next = nil | ||
| Line 33: | Line 37: | ||
| } | } | ||
| - | list.Tail.next = item | + | list.tail.next = item |
| - | item.prev = list.Tail | + | item.prev = list.tail |
| item.next = nil | item.next = nil | ||
| - | list.Tail = item | + | 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 { | func (list *MyList) Count() int { | ||
| count := 0 | count := 0 | ||
| - | for i := list.Head; i != nil; i = i.next { | + | for i := list.head; i != nil; i = i.next { |
| - | count += 1 | + | count++ |
| } | } | ||
| return count | return count | ||
| Line 66: | Line 82: | ||
| fmt.Println(list.Count()) | fmt.Println(list.Count()) | ||
| - | |||
| } | } | ||
| ``` | ``` | ||