-
Notifications
You must be signed in to change notification settings - Fork 23
/
queue.go
78 lines (67 loc) · 1.42 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 algs4
import (
"github.com/shellfly/algo/linklist"
)
// Queue ...
type Queue struct {
first, last *linklist.Node
n int
}
// NewQueue ...
func NewQueue() *Queue {
return &Queue{}
}
// IsEmpty return a bool to indicate if the queue is empty
func (q Queue) IsEmpty() bool {
return q.first == nil
}
// Enqueue add a new item into the queue
func (q *Queue) Enqueue(item interface{}) {
node := linklist.NewNode(item, nil)
oldLast := q.last
q.last = node
if q.IsEmpty() {
q.first = q.last
} else {
oldLast.Next = q.last
}
q.n++
}
// Dequeue add a new item into the queue
func (q *Queue) Dequeue() (item interface{}) {
if q.IsEmpty() {
panic("Queue Empty")
}
item = q.first.Item
q.first = q.first.Next
if q.IsEmpty() {
q.last = nil
}
q.n--
return
}
// Size return the size of the queue
func (q Queue) Size() int {
return q.n
}
// Slice ...
func (q Queue) Slice() (items []interface{}) {
for x := q.first; x != nil; x = x.Next {
items = append(items, x.Item)
}
return
}
// IntSlice returns a slice of int values for iterating
func (q *Queue) IntSlice() (items []int) {
for curr := q.first; curr != nil; curr = curr.Next {
items = append(items, curr.Item.(int))
}
return
}
// StringSlice returns a slice of int values for iterating
func (q *Queue) StringSlice() (items []string) {
for curr := q.first; curr != nil; curr = curr.Next {
items = append(items, curr.Item.(string))
}
return
}