Before diving into the implementation of Linked List in Swift. Let’s start with the basics first.
A linked list is a linear data structure that is made up of different elements called Nodes.
What is Node in Linked List?
A Node is an object which consists of two properties which are value and next. Here, next is the pointer or reference to the next Node which is connected with the current Node.
Node Class in Swift
class Node<Element> {
var value: Element
var next: Node?
init(_ value: Element, next: Node? = nil) {
self.value = value
self.next = next
}
}
let a = Node<Int>(3)
let b = Node<Int>(6)
let c = Node<Int>(9)
a.next = b // Connecting a to b
b.next = c // Connecting b to c
Explanation
- In the above code, I have created a generic Node class. With this class, we can create any type of Node object that holds different data types as its value. So, it can anything like Int, String etc.
- The first property of the Node class is value. It is the value of the current Node. It is compulsory to have some value to initialize the Node class.
- The second property is next. It is the pointer or reference to the next Node. I have declared it as Optional. As it can be nil as well.
- In last, I have created three objects which are a, b and c. Node a is connected to Node b and Node b is connected to Node c.
Also Read – Guard Statement in Swift 5 with Examples – Ultimate Guide
Head and Tail Nodes in Linked List – Swift
Head Node – The first Node in the Linked List is called Head Node.
Tail Node – The last Node in the Linked List is called Tail Node.
Linked List Structure in Swift
struct LinkedList<Element> {
var head: Node<Element>?
var tail: Node<Element>?
init() { }
}
Explanation
- I have declared a Generic struct for the Linked List. Its a Homogenous Linked List which means that All the elements of the Linked List will be of same type.
- First property is head which is of type Node and it holds the reference of some Node.
- Second property is tail which is also of type Node and it holds the reference of some Node as well.
- In Singly Linked List, Tail Node’s next property is always Nil. This is the last node of the Linked List.
Last Words
I hope you will understand the Basics of Linked List in Swift programming language. In the next tutorial, we will learn about the Operations on Linked List.
If you have any doubts or suggestions regarding this article then do comment below.