-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path04_my_queue.go
69 lines (56 loc) · 1.36 KB
/
04_my_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
package ch03
// MyQueue data structure implementation based on two stacks
type MyQueue struct {
// front of the queue (oldest elements)
front *Stack[int]
// back of the queue (newest elements)
back *Stack[int]
}
// NewMyQueue returns new MyQueue
func NewMyQueue() *MyQueue {
return &MyQueue{
front: new(Stack[int]),
back: new(Stack[int]),
}
}
// Enqueue adds an item to the queue
// Time complexity: O(1)
func (q *MyQueue) Enqueue(data int) {
q.back.Push(data)
}
// Dequeue returns (and removes) an item from the queue
// Time complexity: O(n)
func (q *MyQueue) Dequeue() (int, error) {
if err := q.shift(); err != nil {
return 0, err
}
return q.front.Pop()
}
// Peek returns the top item from the queue (without removing it)
// Time complexity: O(n)
func (q *MyQueue) Peek() (int, error) {
if err := q.shift(); err != nil {
return 0, err
}
return q.front.Peek()
}
// IsEmpty returns true when the queue is empty, false otherwise
func (q *MyQueue) IsEmpty() bool {
return q.front.IsEmpty() && q.back.IsEmpty()
}
// shift moves all elements from back to front
func (q *MyQueue) shift() error {
// already have elements in the front, no need to shift
if !q.front.IsEmpty() {
return nil
}
// shift all elements from back to front
for !q.back.IsEmpty() {
data, err := q.back.Pop()
if err != nil {
return nil
}
q.front.Push(data)
}
return nil
}