github.com/iainanderson83/datastructures@v0.0.4-0.20191103204413-889e20b53bcf/linkedlist/linkedlist.go (about) 1 package linkedlist 2 3 type linkedListNode struct { 4 Val interface{} 5 Next *linkedListNode 6 } 7 8 type linkedList struct { 9 root *linkedListNode 10 last *linkedListNode 11 len int 12 } 13 14 func newLinkedList() *linkedList { 15 return &linkedList{} 16 } 17 18 func (l *linkedList) Append(v interface{}) { 19 if v == nil { 20 return 21 } 22 23 node := &linkedListNode{Val: v} 24 25 if l.len == 0 { 26 l.root = node 27 l.last = node 28 } else { 29 last := l.last 30 last.Next = node 31 l.last = node 32 } 33 34 l.len++ 35 } 36 37 func (l *linkedList) Delete(v interface{}) { 38 if v == nil || l.len == 0 { 39 return 40 } 41 42 var prev *linkedListNode 43 node := l.root 44 45 for node.Val != v { 46 if node.Next == nil { 47 return 48 } 49 50 prev = node 51 node = node.Next 52 } 53 54 prev.Next = node.Next 55 l.len-- 56 } 57 58 func (l *linkedList) Insert(v interface{}, less func(i, j interface{}) bool) { 59 if less == nil { 60 l.Append(v) 61 l.len++ 62 return 63 } 64 65 node := &linkedListNode{Val: v} 66 if l.len == 0 { 67 l.root = node 68 l.last = node 69 } else { 70 var prev *linkedListNode 71 curr := l.root 72 73 for less(curr.Val, node.Val) { 74 prev = curr 75 curr = curr.Next 76 } 77 78 prev.Next = node 79 node.Next = curr 80 } 81 82 l.len++ 83 } 84 85 func (l *linkedList) Front() *linkedListNode { 86 return l.root 87 } 88 89 func (l *linkedList) Back() *linkedListNode { 90 return l.last 91 }