Skip to content

Instantly share code, notes, and snippets.

@BrunoCerberus
Created December 24, 2024 03:33
Show Gist options
  • Save BrunoCerberus/e315f626895781cae23bdd912e40e935 to your computer and use it in GitHub Desktop.
Save BrunoCerberus/e315f626895781cae23bdd912e40e935 to your computer and use it in GitHub Desktop.
struct Queue<T> {
private var elements: [T] = []
// Add an element to the back of the queue
mutating func enqueue(_ element: T) {
elements.append(element)
}
// Remove and return the front element
mutating func dequeue() -> T? {
return elements.isEmpty ? nil : elements.removeFirst()
}
// Return the front element without removing it
func peek() -> T? {
return elements.first
}
// Check if the queue is empty
func isEmpty() -> Bool {
return elements.isEmpty
}
// Return the size of the queue
func size() -> Int {
return elements.count
}
}
// Example usage:
var queue = Queue<Int>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) // Prints: Optional(1)
print(queue.peek()) // Prints: Optional(2)
print(queue.size()) // Prints: 2
print(queue.isEmpty()) // Prints: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment