Since our queue is currently empty, let’s add to it! To enqueue literally means “add to the queue”. In creating the enqueue() method, that’s exactly what we’ll do.

When adding a new node to the queue, the new node is always added to the end of the queue.

  • If the queue is empty, the new node becomes the head and tail of the queue. (Imagine only one person is in line).
  • If the queue has at least one other node, the new node becomes the new tail. (Someone joins a line of people).

We can put this into action by creating the enqueue() method of the Queue struct.



Within the Queue struct, declare a method that does not return a value, called enqueue(). It which should accept a parameter for data of type, String, and allow for the argument label to be omitted.

Since we expect this method to alter the queue, don’t forget to add the mutating keyword at the start of the method.


Create a newNode constant that stores an instance of a new Node with the data parameter name passed in for the data property.


Now let’s check if the tail is nil. If it is:

  1. Set the head to be the newNode
  2. Set the tail to be the newNode
  3. Add an empty return

Finally, outside of the guard statement, we want to update the last node’s pointer to the next node and update the tail.

  • Set the lastNode‘s next node to be the new node
  • Set the tail as newNode

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?