github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/linkedlist/list.go (about) 1 // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. 2 3 package linkedlist 4 5 type List[T any] struct { 6 head *Item[T] 7 end *Item[T] 8 count int 9 } 10 11 func NewList[T any]() *List[T] { 12 return &List[T]{} 13 } 14 15 func (this *List[T]) Head() *Item[T] { 16 return this.head 17 } 18 19 func (this *List[T]) End() *Item[T] { 20 return this.end 21 } 22 23 func (this *List[T]) Push(item *Item[T]) { 24 if item == nil { 25 return 26 } 27 28 // 如果已经在末尾了,则do nothing 29 if this.end == item { 30 return 31 } 32 33 if item.prev != nil || item.next != nil || this.head == item { 34 this.Remove(item) 35 } 36 this.add(item) 37 } 38 39 func (this *List[T]) Shift() *Item[T] { 40 if this.head != nil { 41 var old = this.head 42 this.Remove(this.head) 43 return old 44 } 45 return nil 46 } 47 48 func (this *List[T]) Remove(item *Item[T]) { 49 if item == nil { 50 return 51 } 52 if item.prev != nil { 53 item.prev.next = item.next 54 } 55 if item.next != nil { 56 item.next.prev = item.prev 57 } 58 if item == this.head { 59 this.head = item.next 60 } 61 if item == this.end { 62 this.end = item.prev 63 } 64 65 item.prev = nil 66 item.next = nil 67 this.count-- 68 } 69 70 func (this *List[T]) Len() int { 71 return this.count 72 } 73 74 func (this *List[T]) Range(f func(item *Item[T]) (goNext bool)) { 75 for e := this.head; e != nil; e = e.next { 76 goNext := f(e) 77 if !goNext { 78 break 79 } 80 } 81 } 82 83 func (this *List[T]) RangeReverse(f func(item *Item[T]) (goNext bool)) { 84 for e := this.end; e != nil; e = e.prev { 85 goNext := f(e) 86 if !goNext { 87 break 88 } 89 } 90 } 91 92 func (this *List[T]) Reset() { 93 this.head = nil 94 this.end = nil 95 } 96 97 func (this *List[T]) add(item *Item[T]) { 98 if item == nil { 99 return 100 } 101 if this.end != nil { 102 this.end.next = item 103 item.prev = this.end 104 item.next = nil 105 } 106 this.end = item 107 if this.head == nil { 108 this.head = item 109 } 110 this.count++ 111 }