You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
966 B
Go
51 lines
966 B
Go
package container
|
|
|
|
type Queue[T any] struct {
|
|
data []T
|
|
len int
|
|
}
|
|
|
|
// New creates an empty queue
|
|
func NewQueue[T any]() Queue[T] {
|
|
q := Queue[T]{
|
|
[]T{},
|
|
0,
|
|
}
|
|
|
|
return q
|
|
}
|
|
|
|
// Enqueue adds an element to the end of the queue.
|
|
// It appends the given value to the queue's data slice and increments the length of the queue.
|
|
func (q *Queue[T]) Enqueue(v T) {
|
|
q.data = append(q.data, v)
|
|
q.len++
|
|
}
|
|
|
|
// Dequeue removes and returns the element at the front of the queue.
|
|
// It panics if the queue is empty.
|
|
func (q *Queue[T]) Dequeue() T {
|
|
if !q.HasElement() {
|
|
panic("called Dequeue() on an empty queue")
|
|
}
|
|
|
|
value := q.data[0]
|
|
var zeroValue T
|
|
q.data[0] = zeroValue
|
|
q.data = q.data[1:]
|
|
|
|
q.len--
|
|
|
|
return value
|
|
}
|
|
|
|
// HasElement returns true if the queue has at least one element, otherwise false.
|
|
func (q *Queue[T]) HasElement() bool {
|
|
return q.len > 0
|
|
}
|
|
|
|
// GetData returns the data stored in the queue.
|
|
func (q *Queue[T]) GetData() []T {
|
|
return q.data
|
|
}
|