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

Now that we can create sequences of nodes, let’s see them in action!

Imagine we are working at an ice cream shop that sells three flavors: strawberry, banana, and coconut. The signature fruity sundae is made of these three flavors, but our new hires have a hard time remembering the order.

To help them remember, our Swift nodes may do just the trick.

Let’s get started…

Instructions

1.

You’ve been given several ice cream flavors modeled as Node instances. Let’s go through our ice cream nodes to make sure that they are linked in the correct order.

Create a function called printAllNodes() with an argument label of startingAt and a parameter called node with a type of Node. Leave the body of the function empty for now.

The printAllNodes() function will iterate through our ice cream sequence of nodes and print the data stored in each node.

2.

Inside of printAllNodes() create a variable called currentNode of the optional Node type and set it’s initial value to the passed in argument, node.

3.

Next, we’ll create a while loop that only iterates when the currentNode is not nil. (If currentNode evaluates to nil we know that we’ve already visited all the nodes in a sequence.)

On a new line inside printAllNodes()‘s body, create a while loop that checks a constant, unwrappedNode, that is assigned the unwrapped value of currentNode.

Inside the while loop, print the unwrappedNode‘s data, then update currentNode to its .next Node.

4.

Outside of printAllNodes(), call it with the argument of strawberry passed in. You should see the ice cream flavors printed in order of strawberry, banana, and coconut in the terminal.

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?