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:
JessicaNext we will enter Jacob. Notice the name is added below.
Second addition:
Jessica
JacobWe continue with Jayden and Jackson
Third addition:
Jessica
Jacob
JaydenFourth addition:
Jessica
Jacob
Jayden
JacksonEach 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
JacksonJessica 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
JacksonThird iteration:
front returns: Jayden
pop removes: Jayden
Remaining queue:
JacksonFourth 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