-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
68 lines (59 loc) · 1.08 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package tl
type element[T any] struct {
data T
next *element[T]
}
// Queue defines a queue data structure.
type Queue[T any] struct {
first *element[T]
last *element[T]
}
// Reset resets the queue.
func (q *Queue[T]) Reset() {
q.first = nil
q.last = nil
}
// Front returns the first element if any.
func (q *Queue[T]) Front() (v Optional[T]) {
if q.first != nil {
v.Set(q.first.data)
}
return
}
// PushFront pushes `data` to the beginning of the queue.
func (q *Queue[T]) PushFront(data T) {
if q.first == nil {
q.first = &element[T]{
data: data,
}
q.last = q.first
} else {
e := &element[T]{
data: data,
next: q.first,
}
q.first = e
}
}
// PushBack pushes to the back of the queue.
func (q *Queue[T]) PushBack(data T) {
if q.first == nil {
q.first = &element[T]{
data: data,
}
q.last = q.first
} else {
q.last.next = &element[T]{
data: data,
}
q.last = q.last.next
}
}
// Pop pops from the beginning of the queue.
func (q *Queue[T]) Pop() (v Optional[T]) {
if q.first != nil {
v.Set(q.first.data)
q.first = q.first.next
}
return
}