Learn the Queue Data Structure

3 min read

What is a Queue?

A queue is an array-like data structure where elements are ordered first-in, first-out (FIFO). There are two basic operations in a queue.

  • enqueue: insert an element in the back of the queue.
  • dequeue: remove the element that has been in the queue longest.

I want to convince you that you've probably known about queues for a long time.

Queues in the Real World

Let's say you're going grocery shopping. You've picked all of your items and you're ready to check out so you head to the cashiers. What do you see?

You see a queue of people waiting to buy their groceries.

Now, what do you do? You probably don't skip to the front of the queue or skip to somewhere in the middle. That would probably make people waiting upset. You go to the back of the queue.

Who gets service from the cashier next? The person who has been waiting the longest. The next person in line. Customers are served in first in, first out (FIFO) order. A queue is a data structure where elements are added and removed in FIFO order.

Practice with Queues

I hope you now have a mental model for what queues are. Now let's check your understanding. First, I will give an example in pseudocode to show you how a queue behaves.

Pseudocode refers to high-level code that is not associated with any programming language. It's used to give an understanding of how the code works without being detailed about specific syntax.


# first we will define a queue
queue = []

# queue = [1]

# queue = [1, 2]

# queue = [1, 2, 3]

# x = 1, queue = [2, 3]
x = queue.dequeue()

# y = 2, queue = [3]
y = queue.dequeue()

# z = 3, queue = []
z = queue.dequeue()


Now, it's your turn. What are the values of x, y, and z after the following program runs?

queue = []


# x = ???
x = queue.dequeue()


# y = ???
y = queue.dequeue()

# Note, the result of queue.dequeue()
#       is the value passed in as an
#       argument to queue.enqueue()

# z = ???
z = queue.dequeue()

Let me know what you get!

Hey, you! 🫵

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like