Learn

In its entirety, a queue is a data structure that contains an ordered set of data that follows a FIFO (first in, first out) protocol. You can visualize it as a line at a deli:

  • The customer at the front of the line (equivalent to the head in a queue) is the first customer to get served.
  • Any new customer must go to the back of the line (the tail of the queue) and wait until everyone in front of them has been served (no line cutters allowed in this deli!)
  • The deli server only needs to know about the current order.

Now, we can use Swift to build out a Queue struct with those three essential queue methods:

  • enqueue() which will allow us to add a new node to the tail of the queue.
  • dequeue() which will allow us to remove a node from the head of the queue and return its value.
  • peek() which will allow us to view the value of the head of the queue without returning it.

Ready, set, queue up!

Instructions

1.

We will create a basic Queue struct that contains the head and tail as instances of the Node class shown in the editor.

Below the Node class, let’s begin by defining a struct named Queue.

2.

Define two variable-stored properties named head and tail both of optional type 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?