-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharrayqueue.go
87 lines (74 loc) · 1.83 KB
/
arrayqueue.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
79
80
81
82
83
84
85
86
87
package container
// ArrayQueue is an implementation of queue using slice
type ArrayQueue[T any] struct {
arr []T
}
// NewArrayQueue returns a new ArrayQueue object
func NewArrayQueue[T any]() *ArrayQueue[T] {
return &ArrayQueue[T]{arr: make([]T, 0)}
}
// Push adds a new element into the ArrayQueue
func (q *ArrayQueue[T]) Push(x T) {
q.arr = append(q.arr, x)
}
// Pop removes the element at the top of the ArrayQueue and returns the element
// the ArrayQueue must not be empty.
func (q *ArrayQueue[T]) Pop() T {
if q.Len() == 0 {
panic("queue is empty")
}
x := q.arr[0]
q.arr = q.arr[1:]
return x
}
// Top returns the element at the top of the ArrayQueue
// the ArrayQueue must not be empty.
func (q *ArrayQueue[T]) Top() T {
if q.Len() == 0 {
panic("queue is empty")
}
return q.arr[0]
}
// Clear all elemnts in the ArrayQueue
func (q *ArrayQueue[T]) Clear() {
q.arr = q.arr[:0]
}
// Len returns the size of the ArrayQueue
func (q *ArrayQueue[T]) Len() int {
return len(q.arr)
}
/////////////////////////////
///////// Testing ///////////
/////////////////////////////
func checkArrayQueueSize(q *ArrayQueue[int], expect int) {
if q.Len() != expect {
panic(fmt.Sprintf("size check failed, got %d, expect %d", q.Len(), expect))
}
}
func checkArrayQueueNum(got, expect int) {
if got != expect {
panic(fmt.Sprintf("answer does not match, got %d, expect %d", got, expect))
}
}
func testArrayQueue() {
q := NewArrayQueue[int]()
checkArrayQueueSize(q, 0)
q.Push(1)
checkArrayQueueSize(q, 1)
checkArrayQueueNum(q.Top(), 1)
q.Pop()
checkArrayQueueSize(q, 0)
q.Push(1)
q.Push(2)
q.Push(3)
checkArrayQueueSize(q, 3)
checkArrayQueueNum(q.Top(), 1)
q.Pop()
checkArrayQueueSize(q, 2)
checkArrayQueueNum(q.Top(), 2)
q.Pop()
checkArrayQueueSize(q, 1)
checkArrayQueueNum(q.Top(), 3)
q.Clear()
checkArrayQueueSize(q, 0)
}