-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
62 lines (49 loc) · 1.09 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
package pyramid
import "container/heap"
// Queue
// is a list of items.
type Queue[T any] struct {
list []*item[T]
compareFunction compareFunction[T]
}
// Len
// returns the Queue size.
func (pq Queue[T]) Len() int {
return len(pq.list)
}
// Less
// comparator function.
func (pq Queue[T]) Less(i, j int) bool {
return pq.compareFunction(pq.list[i].value, pq.list[j].value)
}
// Swap
// function for Queue.
func (pq Queue[T]) Swap(i, j int) {
pq.list[i], pq.list[j] = pq.list[j], pq.list[i]
pq.list[i].index = i
pq.list[j].index = j
}
// Push
// new items to Queue list.
func (pq *Queue[T]) Push(x any) {
n := len(pq.list)
i := &item[T]{value: x.(T), index: n}
pq.list = append(pq.list, i)
}
// Pop
// extract one item from Queue list.
func (pq *Queue[T]) Pop() any {
old := pq.list
n := len(old)
i := old[n-1]
old[n-1] = nil // avoid memory leak
i.index = -1 // for safety
pq.list = old[0 : n-1]
return i.value
}
// update
// modifies the priority and value of an Item in the queue.
func (pq *Queue[T]) update(i *item[T], value T) {
i.value = value
heap.Fix(pq, i.index)
}