A queue is exactly what you think it would be, similar to its dictionary definition. It’s an ordered list of elements with a “FIFO” principle.
“FIFO” stands for “First In, First Out” — the first element that is inserted into the queue will also be the first element that is removed from the queue.
Imagine a grocery line, where the first customer in line will be the first customer to get their groceries rung up and exit the store. If the first customer in line were to take a long time or to just refuse to exit the store, the rest of the customers in line will be held up. Because it’s an ordered line, a random customer cannot go to the register to get rung up.
Queues have three main operations: inserting an element at the end of the list (enqueue), removing an element at the front of the list (dequeue), and returning the first element of the list without modifying the list (peek).
With all data structures, there are advantages and disadvantages to using a queue.
Advantages + Disadvantages
Queues are dynamic in size and often don’t take up too much space, leading to its low runtime. Another advantage is that the data is ordered in the way it is received — great for applications that utilize messages (like voicemails). Queues also guarantee that the oldest information will always be processed first.
The main and often only disadvantage is that you can only retrieve the oldest element at all times.
Like I mentioned before, next week I’ll be discussing how to implement a queue using an array!