A queue data structure is like a line of people waiting. A queue is an example of a First-In-First-Out (FIFO) data structure. Queues are very useful when there is an order of operations that must be followed. There are 2 essential operations when implementing a queue: enqueue and dequeue, which handle the addition and removal of elements to and from the queue, respectively.
Here is a simple array-based implementation of a queue:
public struct Queue<Element> {
private var queue: [Element] = []
mutating func enqueue(_ element: Element) { // O(1) operation
queue.append(enqueue)
}
@discardableResult
mutating func dequeue() -> Element? { // O(n) operation
queue.removeFirst()
}
var isEmpty: Bool {
queue.isEmpty
}
var peek: Element? {
queue.first
}
}
Tags: tech, data_structures_algorithms