Learn

Currently, we don’t have an easy way of printing a linked list in a format that tells us about the nodes or data stored in them.

For example, printing the linked list that stores the plants in a greenhouse in the code snippet below results in the text Node.LinkedList being output in the terminal.

let greenhouse = LinkedList() greenhouse.append("Bamboo") greenhouse.append("Golden Pothos") greenhouse.append("Snake Plant") print(greenhouse) // Prints Node.LinkedList

To test the append(:_) method we created, let’s create an extension to the LinkedList class using the CustomStringConvertible protocol. This extension will convert a linked list to a formatted String whenever the print(_:separator:terminator:) function is used.

The new LinkedList extension should do the following:

  1. Format the data stored in each node from head to tail

  2. Indicate the direction of the linked list by joining the data of each node with an arrow -> and spaces

  3. Return the text nil when the linked list is empty

Let’s get printing!

Instructions

1.

In the editor, you’ll find your code from the previous exercise plus code for a Node extension that formats a string representation of a Node instance. Your LinkedList extension will make use of the Node extension.

Take a moment to read over what the Node extension will do when a node is printed.

2.

Create an extension to the LinkedList class that uses the CustomStringConvertible protocol.

You will see an error message that mentions this protocol requires a property named description. In the following step, you’ll add code to fix this.

3.

You saw that the Node extension will return data stored in a chain of nodes as a formatted string. The LinkedList extension should say what node to start building that formatted string from.

Create a computed property named description of type String. This property will return your representation of a LinkedList whenever it needs to be converted to text.

Inside the closure of description, use optional chaining to access the head of the linked list and call the Node property of the same name, description, on it. Use the nil coalescing operator ?? to return a default value of nil if there is no head.

4.

Test both the append(:_) method from the previous exercise and the LinkedList extension.

Outside and after the LinkedList extension, create a constant called germanCars and set it to a LinkedList instance. Then call append(:_) three times with the following names of car brands:

  • “Volkswagen”
  • “Porsche”
  • “Audi”
5.

Print your updated linked list, germanCars. You should see the following text printed in the output terminal, showing each node’s data and next node, going from the head to the tail:

Volkswagen -> Porsche -> 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?