You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
844 B

5 years ago
  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. }