We can add items to the tail of our queue, but when we remove them, we remove them from the head. Remember that this protocol is described as first in, first out (FIFO). The method that performs this is called dequeue()
, or “remove from the queue”.
This method removes the head node and replaces it with the following node. It also returns the head node.
- If the queue has one node, when we remove it, the queue will be empty. (Imagine only one person was in line).
- If the queue has more than one node, we remove the head node and reset the head to the following node. (Once the first person places their order, the next person in line moves up).
Let’s add this functionality to our Queue structure next.
Instructions
Declare a method called dequeue()
and declare its return type as an optional String
. Don’t forget to use the mutating
keyword before the function name. For now, have the function return nil
so that there isn’t a compilation error.
We’ll need a variable that will store and return the removed node. Declare this variable, removedNode
, of type optional String.
Since this method removes the head node, we’ll first need to check if the head node is not nil. Set up an empty if-let
statement that creates a temporary variable, firstNode
, and assigns it to head
.
If the head
and the tail
are both the same node, that means that the queue should be empty after dequeue
is called, and tail
should be nil
. Use an if statement and the ===
operator to check to see if the head
and tail
have the same identity. If they are, assign tail
to nil
.
Outside of the if-let
statement, update the head to be the next node. Then, return the removed node.