4.5.3 Queue Example: Next in Line

In this example, we are adding name to a virtual line using a queue.

Letโ€™s walk through a simple example where we will add 4 names, Jessica, Jacob, Jayden, and Jackson.

Letโ€™s put our four names in, in order. First, we add Jessica

First addition:
Jessica

Next we will enter Jacob. Notice the name is added below.

Second addition:
Jessica
Jacob

We continue with Jayden and Jackson

Third addition:
Jessica
Jacob
Jayden
Fourth addition:
Jessica
Jacob
Jayden
Jackson

Each time, the new name is added to the back of the list, just like the person is joining the virtual line at the back.

Now letโ€™s take a look at how the names are removed:

First iteration:
front returns: Jessica
pop removes: Jessica
Remaining queue:
Jacob
Jayden
Jackson

Jessica got in line first, so she is the first to come off the queue.

Second iteration:
front returns: Jacob
pop removes: Jacob
Remaining queue:
Jayden
Jackson
Third iteration:
front returns: Jayden
pop removes: Jayden
Remaining queue:
Jackson
Fourth iteration:
front returns: Jackson
pop removes: Jackson
Remaining queue:
(queue is empty)

Notice how we access each name in the queue with the front command and then remove the name with the pop command. Once removed, this name is lost, so there is no way to loop through and view each name without removing it entirely from the queue.

Last updated