queue.go 844 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package util
  2. import (
  3. "sync"
  4. )
  5. type node[T any]struct {
  6. data T
  7. next *node[T]
  8. }
  9. type Queue[T any] struct {
  10. head *node[T]
  11. tail *node[T]
  12. count int
  13. sync.RWMutex
  14. }
  15. func NewQueue[T any]() *Queue[T] {
  16. q := &Queue[T]{}
  17. return q
  18. }
  19. func (q *Queue[T]) Len() int {
  20. q.RLock()
  21. defer q.RUnlock()
  22. return q.count
  23. }
  24. func (q *Queue[T]) Enqueue(item T) {
  25. q.Lock()
  26. defer q.Unlock()
  27. n := &node[T]{data: item}
  28. if q.tail == nil {
  29. q.tail = n
  30. q.head = n
  31. } else {
  32. q.tail.next = n
  33. q.tail = n
  34. }
  35. q.count++
  36. }
  37. func (q *Queue[T]) Dequeue() (result T) {
  38. q.Lock()
  39. defer q.Unlock()
  40. if q.head == nil {
  41. return
  42. }
  43. n := q.head
  44. q.head = n.next
  45. if q.head == nil {
  46. q.tail = nil
  47. }
  48. q.count--
  49. return n.data
  50. }
  51. func (q *Queue[T]) Peek() (result T) {
  52. q.RLock()
  53. defer q.RUnlock()
  54. if q.head == nil {
  55. return
  56. }
  57. return q.head.data
  58. }