Holger Hildebrandt | 0f9b88d | 2020-04-20 13:33:25 +0000 | [diff] [blame] | 1 | package ordered_map |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "bytes" |
| 6 | ) |
| 7 | |
| 8 | type node struct { |
| 9 | Prev *node |
| 10 | Next *node |
| 11 | Value interface{} |
| 12 | } |
| 13 | |
| 14 | func newRootNode() *node { |
| 15 | root := &node{} |
| 16 | root.Prev = root |
| 17 | root.Next = root |
| 18 | return root |
| 19 | } |
| 20 | |
| 21 | func newNode(prev *node, next *node, key interface{}) *node { |
| 22 | return &node{Prev: prev, Next: next, Value: key} |
| 23 | } |
| 24 | |
| 25 | func (n *node) Add(value string) { |
| 26 | root := n |
| 27 | last := root.Prev |
| 28 | last.Next = newNode(last, n, value) |
| 29 | root.Prev = last.Next |
| 30 | } |
| 31 | |
| 32 | func (n *node) String() string { |
| 33 | var buffer bytes.Buffer |
| 34 | if n.Value == "" { |
| 35 | // Need to sentinel |
| 36 | var curr *node |
| 37 | root := n |
| 38 | curr = root.Next |
| 39 | for curr != root { |
| 40 | buffer.WriteString(fmt.Sprintf("%s, ", curr.Value)) |
| 41 | curr = curr.Next |
| 42 | } |
| 43 | } else { |
| 44 | // Else, print pointer value |
| 45 | buffer.WriteString(fmt.Sprintf("%p, ", &n)) |
| 46 | } |
| 47 | return fmt.Sprintf("LinkList[%v]", buffer.String()) |
| 48 | } |
| 49 | |
| 50 | func (n *node) IterFunc() func() (string, bool) { |
| 51 | var curr *node |
| 52 | root := n |
| 53 | curr = root.Next |
| 54 | return func() (string, bool) { |
| 55 | for curr != root { |
| 56 | tmp := curr.Value.(string) |
| 57 | curr = curr.Next |
| 58 | return tmp, true |
| 59 | } |
| 60 | return "", false |
| 61 | } |
| 62 | } |