Linked Lists and LL Algorithms in Swift

Photo by Markus Spiske on Unsplash

Prerequisites:

  • Coding in Swift Playgrounds (guide HERE)
  • While loops in Swift (guide HERE)

Terminology

Swift terminology

Class: An object that defines properties and methods in common

Linked List Terminology

Data structure: A way of formatting data

Implementing a Node in Swift -Integer

A choice has been made to implement a node that contains an Integer as the data payload. If you wish to see a node that is generic (that is, can carry any data) please see the second half of this article.

The setup for a node (the class)

Since our Node class needs to reference itself, a class has been chosen to represent the Node type (although an enum is a value type that can reference itself, I have chosen not to use that type to represent a Node in this case)

Create instances of a node

In terms of creating an instance of a Node, Swift helps us out just as if we are creating an instance of any class.

__lldb_expr_10.Node

Make the Node conform to CustomStringConvertable

When we conform to CustomStringConvertable we need to provide a description that Swift will provide when we print the element.

Data: 0 { Data: 1 { Data: 2 { null } } }

Reading out the data from a Linked List

Here we are going to use a while loop to traverse the linked list. We know when we have gone to the end of the linked list since the last element always points to nil!

0
1
2

Remove an element

Remove a node from the head of the linked list

Conclusion:

Linked lists are really important in programming, and this guide has shown you how linked lists can be implemented in the best programming language (Swift).

The Twitter contact:

Any questions? You can get in touch with me HERE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store