Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Algorithms and Linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

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

1.

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.

2.

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.

3.

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.

4.

Outside of the if-let statement, update the head to be the next node. Then, return the removed node.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?