forked from betty200744/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
49 lines (47 loc) · 816 Bytes
/
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
package queue
/*
定长
first-in , first-out
+---+---+---+
enqueue -> | 3 | 2 | 1 | -> dequeue
+---+---+---+
*/
/*
IsEmpty() bool
Peek() (interface{}, error)
Enqueue(value interface{})
Dequeue() interface{}
*/
/*
现实场景如: 消息队列,kafka, rabbitmq
*/
type Queue struct {
queue []interface{}
len int
}
func New() *Queue {
queue := &Queue{
queue: []interface{}{},
len: 0,
}
return queue
}
func (q *Queue) IsEmpty() bool {
return len(q.queue) == 0
}
func (q *Queue) Peek() (interface{}, bool) {
if len(q.queue) == 0 {
return nil, false
}
return q.queue[0], true
}
func (q *Queue) Enqueue(value interface{}) {
q.queue = append(q.queue, value)
q.len++
}
func (q *Queue) Dequeue() interface{} {
el := q.queue[0]
q.queue = q.queue[1:]
q.len--
return el
}