queue

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 1, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Queue

type Queue[T any] struct {
	// contains filtered or unexported fields
}

Queue represents a generic FIFO queue data structure. Elements are added to the back and removed from the front. The zero value is not usable; use NewQueue to create a new Queue.

func NewQueue

func NewQueue[T any]() *Queue[T]

NewQueue creates and returns an empty queue that can store elements of type T.

Example:

q := NewQueue[int]()
q.Enqueue(1)

func (*Queue[T]) Dequeue

func (q *Queue[T]) Dequeue() (T, bool)

Dequeue removes and returns the element at the front of the queue. Returns the element and true if successful, or zero value and false if the queue is empty.

Example:

q := NewQueue[int]()
q.Enqueue(1)
q.Enqueue(2)
val, ok := q.Dequeue() // val = 1, ok = true
val, ok = q.Dequeue()  // val = 2, ok = true
val, ok = q.Dequeue()  // val = 0, ok = false (queue empty)

func (*Queue[T]) Enqueue

func (q *Queue[T]) Enqueue(element T)

Enqueue adds an element to the back of the queue.

Example:

q := NewQueue[int]()
q.Enqueue(1) // queue now contains: [1]
q.Enqueue(2) // queue now contains: [1, 2]

func (*Queue[T]) IsEmpty

func (q *Queue[T]) IsEmpty() bool

IsEmpty returns true if the queue contains no elements, false otherwise.

Example:

q := NewQueue[int]()
fmt.Println(q.IsEmpty()) // Output: true
q.Enqueue(1)
fmt.Println(q.IsEmpty()) // Output: false

func (*Queue[T]) Length

func (q *Queue[T]) Length() int

Length returns the number of elements currently in the queue.

Example:

q := NewQueue[int]()
q.Enqueue(1)
q.Enqueue(2)
fmt.Println(q.Length()) // Output: 2

func (*Queue[T]) Peek

func (q *Queue[T]) Peek() (T, bool)

Peek returns the element at the front of the queue without removing it. Returns the element and true if successful, or zero value and false if the queue is empty.

Example:

q := NewQueue[int]()
q.Enqueue(1)
val, ok := q.Peek() // val = 1, ok = true, queue still contains: [1]

func (*Queue[T]) PreventDuplicates added in v0.2.1

func (q *Queue[T]) PreventDuplicates(equalsFunc func(a, b T) bool) error

PreventDuplicates will prevent duplicates being added to the queue, giving it Set qualities. Returns an error if the generic T is not Comparable

Example:

q := NewQueue[ContactUser]()
q.PreventDuplicates(func(a, b ContactUser) bool {
    return a.Email == b.Email
})
q.Enqueue(ContactUser{Email: "alice@example.com"})
q.Enqueue(ContactUser{Email: "bob@example.com"})
q.Enqueue(ContactUser{Email: "alice@example.com"})
fmt.Println(q.Length()) // Output: 2

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL