github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/collection/listx/queue.go (about) 1 //nolint:dupl 2 package listx 3 4 // Queue is a First In First Out data structure implementation. 5 // The zero value for Queue is an empty queue ready to use. 6 // A Queue is not safe for concurrent operations. 7 type Queue[T any] struct { 8 l List[T] 9 } 10 11 // NewQueue creates a new Queue instance. 12 func NewQueue[T any]() *Queue[T] { 13 return &Queue[T]{} 14 } 15 16 // Len returns the size of the Queue. 17 func (q *Queue[T]) Len() int { 18 return q.l.Len() 19 } 20 21 // Enqueue adds an item at the back of the Queue in *O(1)* time complexity. 22 func (q *Queue[T]) Enqueue(item T) { 23 q.l.PushFront(item) 24 } 25 26 // Dequeue removes and returns the Queue's front item in *O(1)* time complexity. 27 func (q *Queue[T]) Dequeue() (item T, ok bool) { 28 last := q.l.Back() 29 if last != nil { 30 item = q.l.Remove(last) 31 ok = true 32 } 33 return 34 } 35 36 // Peek returns the Queue's front item in *O(1)* time complexity, 37 // it does not remove the item from the Queue. 38 func (q *Queue[T]) Peek() (item T, ok bool) { 39 last := q.l.Back() 40 if last != nil { 41 item, ok = last.Value.(T), true 42 } 43 return 44 }