Junior — Middle
Can you explain the term 'queue' in the context of data structures?
sobes.tech AI
Answer from AI
A queue is a data structure that operates on the FIFO (First In, First Out) principle, meaning the first element to arrive will be the first to be processed. Imagine a queue at a store: the first person in line is the first to be served.
In programming, a queue is used when there is a need to order data or tasks for processing, such as in event handling, task scheduling, or data buffering.
Example in Swift using Array as a queue:
var queue = [Int]()
// Adding an element to the queue
queue.append(1)
queue.append(2)
// Removing an element from the queue
if let first = queue.first {
print("Processing element: \(first)")
queue.removeFirst()
}