Let’s add some more functionality to our LinkedList
class. If we can retrieve all the nodes from a linked list, we should also be able to access a specific node depending on its position.
Just like appending to a linked list, we’ll create a new method to find and return the data of a node at a specific index. This function should have a runtime efficiency of Θ(n)
since the worst-case scenario would be to search through the entire length of the chain of nodes, n
, for a node.
Instructions
Create a function inside of the LinkedList
class called getNode
. It should return a Node
optional, have a parameter label at
, and a single parameter named index
of the Int
type.
The only valid indices accepted should be a positive number or zero.
Add a guard
statement inside getNode(at:)
that checks whether the index is greater than or equal to 0
,otherwise return out of the function with nil
if it is not.
If the index passes the guard statement, getNode(at:)
should loop over each of the nodes in the linked list starting with the head.
Create a variable called current
that is initialized with the head of the linked list.
Create a for
loop to traverse the nodes in the linked list. It should start from the head and stop before the node at the index we want to access.
Indicate that the iteration variable will not be used by using the underscore, _
instead of a variable name.
The for
loop should only update current
if there is a node after it to visit.
Inside the for
loop, guard the current
node’s next node in a constant called next
. If there is no next node, return nil
.
If a node exists after the node the for
loop is currently on, current
should be updated.
After the guard
statement, update current
to current
‘s next node.
If getNode(at:)
has not returned nil
and the loop has completed running, a node exists at the index.
After the for
loop, return the current node.
Test your code. On a new line after your print statement for germanCars
, print the result of calling your new method getNode(at:)
with an index of 1
. Then print the result of calling getNode(at:)
with an index of 2
.
You should see the following printed in the terminal:
Porsche -> Audi -> nil Audi -> nil