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.
Instructions
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:
- Set the
head
to be thenewNode
- Set the
tail
to be thenewNode
- 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
‘snext
node to be the new node - Set the
tail
asnewNode