Let’s implement a linked list in Swift. As you might recall, a linked list is a sequential chain of nodes.
Remember that a node contains data and a link to the next node.
We are going to use the
Node class you created in the last lesson. The code for the class
Node can be found in the code editor of each exercise.
Depending on the end-use of the linked list, there are a variety of methods that we can define. For our use, we want to be able to:
- add a new node to the end (tail) of the list
- print out the nodes in the list in order from head to tail
- retrieve a node according to its position remove a node from the list according to its position
Ready? Let’s get started!
To start, we are going to build out a
LinkedList class with variable stored properties and an initializer.
Create a class named
LinkedList that will model a linked list data structure.
The linked list class should keep track of what the first node in the list is.
Add a variable stored property named
head of an optional
Node to the
Just as a linked list should track its first node, it should also keep track of its last node.
Add another variable stored property to
LinkedList of an optional
Node. Name this variable stored property