create a linked list in swift in swift

To create a linked list in Swift, first, you need to define a Node class that will be used to create nodes of the linked list.

Each node will hold a value and a reference to the next node in the list. If the node is the last one, the reference to the next node will be nil.

main.swift
class Node<T> {
    var value: T
    var next: Node<T>?

    init(_ value: T, _ next: Node<T>? = nil) {
        self.value = value
        self.next = next
    }
}
164 chars
10 lines

Once the Node class is defined, you can define a LinkedList class that will keep track of the head of the list and provide operations to interact with the list.

main.swift
class LinkedList<T> {
    var head: Node<T>?

    func insertFirst(_ value: T) {
        head = Node(value, head)
    }

    func insertLast(_ value: T) {
        guard head != nil else {
            insertFirst(value)
            return
        }

        var current = head

        while current?.next != nil {
            current = current?.next
        }

        current?.next = Node(value)
    }

    func delete(_ value: T) {
        guard head?.value != nil else { return }

        if head?.value == value {
            head = head?.next
            return
        }

        var current = head
        var prev: Node<T>?

        while current?.value != value && current?.next != nil {
            prev = current
            current = current?.next
        }

        prev?.next = current?.next
    }

    func displayList() {
        var current = head

        while current != nil {
            print(current?.value as Any)
            current = current?.next
        }
    }
}
992 chars
51 lines

With the LinkedList class, you can create an instance of a linked list and use the available operations to manipulate it.

main.swift
let myList = LinkedList<Int>()

myList.insertFirst(5)
myList.insertLast(10)
myList.delete(5)

myList.displayList() // Output: 10
129 chars
8 lines

gistlibby LogSnag