CS Level Up Series (29 Part Series)
- Queues, like IRL (except when a Chat & Cut occurs), are FIFO (First In First Out). As opposed to Stacks, which are LIFO (see previous post).
- Like Stacks, Queues have fast operations: adding (enqueuing), removing (dequeuing), and checking the front (peeking) are all O(1) (constant).
- Like Stacks, a Queue's space is O(n).
- Queues can be implemented using arrays, but it's not a great idea* (my implementation is using an array for simplicity). They can also be implemented with Linked Lists.
*The dequeue operation is O(n) (linear) when using an array. This is because all the elements of the array need to be moved towards the front. In a Linked List implementation, just the Head node needs to get removed, and whatever node it pointed to made the new Head. This is further explained in the Brilliant article.
A good real-world use case for Queues, per InterviewCake:
Printers use queues to manage jobs—jobs get printed in the order they're submitted
Overall learning about Queues is similar in complexity to Stacks, slightly more advanced but not by much. Below you'll find the finished implementation with test code.
Please note that the implementation is very simplistic. Elements are never actually removed from the array (as with my prior Stack implementation) - this also means the dequeue doesn't move any elements to the front and is O(1):
As always, if you found any errors in this post please let me know!
You're one click away
Level up every day