-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
78 lines (69 loc) · 1.34 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
69
70
71
72
73
74
75
76
77
78
package trygo
import (
"container/list"
"reflect"
)
// Queue struct
type Queue struct {
sem chan int
list *list.List
}
var tFunc func(val interface{}) bool
// NewQueue create a new Queue and return.
func NewQueue() *Queue {
sem := make(chan int, 1)
list := list.New()
return &Queue{sem, list}
}
// Size get size of the queue
func (q *Queue) Size() int {
return q.list.Len()
}
// Enqueue puts an element into queue.
func (q *Queue) Enqueue(val interface{}) *list.Element {
q.sem <- 1
e := q.list.PushFront(val)
<-q.sem
return e
}
// Dequeue puts an element out of the queue.
func (q *Queue) Dequeue() *list.Element {
q.sem <- 1
e := q.list.Back()
q.list.Remove(e)
<-q.sem
return e
}
// Query returns the element in the queue only if func queueFunc(element) returns true..
func (q *Queue) Query(queryFunc interface{}) *list.Element {
q.sem <- 1
e := q.list.Front()
for e != nil {
if reflect.TypeOf(queryFunc) == reflect.TypeOf(tFunc) {
if queryFunc.(func(val interface{}) bool)(e.Value) {
<-q.sem
return e
}
} else {
<-q.sem
return nil
}
e = e.Next()
}
<-q.sem
return nil
}
// Contain tests if this item in the queue.
func (q *Queue) Contain(val interface{}) bool {
q.sem <- 1
e := q.list.Front()
for e != nil {
if e.Value == val {
<-q.sem
return true
}
e = e.Next()
}
<-q.sem
return false
}