How do I implement a linked list in Swift?

A linked list is a data structure that consists of a sequence of elements, each linked to the next by references. In Swift, implementing a linked list allows you to create a dynamic data structure that can grow or shrink in size as needed.

Implementing a Linked List in Swift

The following is an example of how to implement a simple singly linked list in Swift.

class Node { var value: Int var next: Node? init(value: Int) { self.value = value self.next = nil } } class LinkedList { var head: Node? func append(value: Int) { let newNode = Node(value: value) if head == nil { head = newNode } else { var currentNode = head while currentNode?.next != nil { currentNode = currentNode?.next } currentNode?.next = newNode } } func display() { var currentNode = head while currentNode != nil { print(currentNode!.value) currentNode = currentNode?.next } } } let list = LinkedList() list.append(value: 1) list.append(value: 2) list.append(value: 3) list.display() // Output: 1 2 3

Linked List Swift Implementation Data Structures Node Dynamic Data Structure