We now have a linked list class! But any linked list we create is empty and stays that way, which isn’t very useful.
In this exercise, we’ll give LinkedList
instances the ability to add nodes by making use of the previously defined Node
class.
We’ll create a LinkedList
instance method that will hold the code needed to store data in a node and update the variable stored properties of the linked list as well as the nodes in it.
The runtime efficiency of our append function should be constant, or Θ(1)
. Since we are adding nodes to the tail
, which we always have a reference to, the runtime is the same for all linked lists, no matter how many nodes are in them.
Instructions
Start by defining a LinkedList
method called append
. It should have a parameter named data
of String
type and return nothing. Allow the method to be called without an argument label.
The method, append(_:)
, should accept the data
passed into it for a node.
Create a new Node
instance with the data retrieved from the function call. Store this node in a constant, newNode
.
Now that the data is stored in a Node
instance, it can be attached to the linked list by updating the variable stored properties of the linked list and the tail.
After the declaration for newNode
, use optional binding to check if the linked list’s tail already references a node. Within the if
statement, create a constant named lastNode
that stores the tail. If the lastNode
is not nil
, set lastNode
‘s next node to newNode
.
If a linked list is empty, the head needs to update from nil
to the node being appended.
Add an else
statement to the if
statement. Inside the else
statement’s closure, update the head of the linked list to newNode
.
A linked list, whether empty or not, will need to have its tail updated.
Outside of the previous conditional statements you added to append(_:)
, set the linked list’s tail to newNode
.