-
-
Notifications
You must be signed in to change notification settings - Fork 703
/
queue.go
52 lines (41 loc) · 1.05 KB
/
queue.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package util
// Queue is based on https://github.com/golang-ds/queue
type Queue[T any] struct {
data []T
}
// NewQueue constructs and returns an empty slice-queue.
func NewQueue[T any]() *Queue[T] {
return new(Queue[T])
}
// Enqueue adds an element to the end of the queue.
func (q *Queue[T]) Enqueue(data T) {
q.data = append(q.data, data)
}
// Dequeue removes and returns the front element of the queue. It returns false if the queue was empty.
func (q *Queue[T]) Dequeue() (val T, ok bool) {
if q.IsEmpty() {
return
}
val = q.data[0]
q.data = q.data[1:]
return val, true
}
// First returns the front element of the queue. It returns false if the queue was empty.
func (q *Queue[T]) First() (val T, ok bool) {
if q.IsEmpty() {
return
}
return q.data[0], true
}
// Size returns the number of the elements in the queue.
func (q *Queue[T]) Size() int {
return len(q.data)
}
// Clear empties the queue.
func (q *Queue[T]) Clear() {
q.data = nil
}
// IsEmpty returns true if the queue is empty.
func (q *Queue[T]) IsEmpty() bool {
return q.Size() == 0
}