Last active
July 24, 2023 16:38
-
-
Save maxclav/41a9f3cbd266b83162930efec6ed1a68 to your computer and use it in GitHub Desktop.
Queue Data Structure with generics in Go (GoLang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package queue | |
// Queue represents a generic queue data structure. | |
type Queue[T any] struct { | |
items []T | |
} | |
// Enqueue adds an item to the end of the queue. | |
func (q *Queue[T]) Enqueue(item T) { | |
q.items = append(q.items, item) | |
} | |
// Dequeue removes and returns the item from the front of the queue. | |
// It also returns a boolean value indicating whether the queue is empty. | |
func (q *Queue[T]) Dequeue() (T, bool) { | |
if len(q.items) == 0 { | |
var noop T | |
return noop, false | |
} | |
item := q.items[0] | |
q.items = q.items[1:] | |
return item, true | |
} | |
// IsEmpty checks if the queue is empty. | |
func (q *Queue[T]) IsEmpty() bool { | |
return len(q.items) == 0 | |
} | |
// Size returns the number of elements in the queue. | |
func (q *Queue[T]) Size() int { | |
return len(q.items) | |
} | |
// Front returns the item at the front of the queue without removing it. | |
func (q *Queue[T]) Front() (T, bool) { | |
if len(q.items) == 0 { | |
var noop T | |
return noop, false | |
} | |
return q.items[0], true | |
} |
Author
maxclav
commented
Jul 24, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment