-
Notifications
You must be signed in to change notification settings - Fork 7
/
priorityqueue_example.go
101 lines (75 loc) · 2.31 KB
/
priorityqueue_example.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (c) 2019, Benjamin Wang ([email protected]). All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package main
import (
"fmt"
"github.com/ahrtr/gocontainer/queue/priorityqueue"
)
func priorityqueueExample1() {
pq := priorityqueue.New()
values := []string{"benjamin", "alice", "john", "tom", "bill"}
for _, v := range values {
pq.Add(v)
}
for _, v := range values {
fmt.Printf("pq.Contains(%v) = %t\n", v, pq.Contains(v))
}
fmt.Printf("pq.Remove(john) = %t\n", pq.Remove("john"))
for pq.Peek() != nil {
fmt.Printf("pq.Peek() = %v\n", pq.Peek())
fmt.Printf("pq.Poll() = %v\n", pq.Poll())
}
}
// priorityqueueExample2 demos how to reverse order for the build-in data types.
func priorityqueueExample2() {
pq := priorityqueue.New().WithMinHeap(false)
values := []string{"benjamin", "alice", "john", "tom", "bill"}
for _, v := range values {
pq.Add(v)
}
for _, v := range values {
fmt.Printf("pq.Contains(%v) = %t\n", v, pq.Contains(v))
}
fmt.Printf("pq.Remove(john) = %t\n", pq.Remove("john"))
for pq.Peek() != nil {
fmt.Printf("pq.Peek() = %v\n", pq.Peek())
fmt.Printf("pq.Poll() = %v\n", pq.Poll())
}
}
// priorityqueueExample3 demos how to reverse order for the build-in data types using a comparator.
func priorityqueueExample3() {
pq := priorityqueue.New().WithComparator(&reverseString{})
values := []string{"benjamin", "alice", "john", "tom", "bill"}
for _, v := range values {
pq.Add(v)
}
for _, v := range values {
fmt.Printf("pq.Contains(%v) = %t\n", v, pq.Contains(v))
}
fmt.Printf("pq.Remove(john) = %t\n", pq.Remove("john"))
for pq.Peek() != nil {
fmt.Printf("pq.Peek() = %v\n", pq.Peek())
fmt.Printf("pq.Poll() = %v\n", pq.Poll())
}
}
// priorityqueueExample3 demos how to order the customized data types (struct).
func priorityqueueExample4() {
pq := priorityqueue.New().WithComparator(&student{})
values := []student{
{name: "benjamin", age: 28},
{name: "alice", age: 42},
{name: "john", age: 35},
{name: "tom", age: 18},
{name: "bill", age: 25},
}
for _, v := range values {
pq.Add(v)
}
for _, v := range values {
fmt.Printf("pq.Contains(%v) = %t\n", v, pq.Contains(v))
}
for pq.Peek() != nil {
fmt.Printf("pq.Peek() = %v\n", pq.Peek())
fmt.Printf("pq.Poll() = %v\n", pq.Poll())
}
}