-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
58 lines (44 loc) · 884 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
50
51
52
53
54
55
56
57
58
package main
import "errors"
type Queue struct {
High []int
Low []int
}
func NewQueue() *Queue {
return &Queue{}
}
func (q *Queue) Enqueue(val int, highPriority bool) Queue {
if highPriority {
q.High = append(q.High, val)
} else {
q.Low = append(q.Low, val)
}
return *q
}
func (q Queue) Size() int {
return len(q.High) + len(q.Low)
}
func (q Queue) IsEmpty() bool {
return q.Size() < 1
}
func (q *Queue) Dequeue() (int, error) {
if q.IsEmpty() {
return 0, errors.New("queue is empty")
}
var firstElement int
if len(q.High) > 1 {
firstElement, q.High = q.High[0], q.High[1:]
return firstElement, nil
}
firstElement, q.Low = q.Low[0], q.Low[1:]
return firstElement, nil
}
func (q *Queue) Peek() (int, error) {
if q.IsEmpty() {
return 0, errors.New("queue is empty")
}
if len(q.High) > 0 {
return q.High[0], nil
}
return q.Low[0], nil
}