Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Algorithms and Linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

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

1.

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.

2.

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.

3.

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.

4.

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.

5.

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.

6.

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.

7.

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.

8.

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

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?