-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
58 lines (51 loc) · 1.04 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
package queue
type element[V any] struct {
val V
next *element[V]
}
// Queue represents a queue data structure. It is a FIFO (first in first out) data
// structure, which means that the first element added to the queue will be the
// first one to be removed.
type Queue[V any] struct {
head *element[V]
tail *element[V]
len int
}
// New returns a new queue.
func New[V any]() *Queue[V] {
dummy := &element[V]{}
return &Queue[V]{
head: dummy,
tail: dummy,
len: 0,
}
}
// Len returns the number of elements in the queue.
func (q *Queue[V]) Len() int {
return q.len
}
// Push adds an element to the queue.
func (q *Queue[V]) Push(v V) {
e := &element[V]{val: v}
q.tail.next = e
q.tail = e
q.len++
}
// Peek returns the first element in the queue.
func (q *Queue[V]) Peek() *V {
if q.len == 0 {
return nil
}
return &q.head.next.val
}
// Pop removes and returns the first element in the queue.
func (q *Queue[V]) Pop() *V {
if q.len == 0 {
return nil
}
e := q.head.next
q.head.next = e.next
q.len--
e.next = nil
return &e.val
}