add a node to the end of a linked list in swift

To add a node to the end of a linked list in Swift, you can follow the steps below:

First, create a new node that you want to add to the end of the list:

main.swift
class Node<T> {
    var value: T
    var next: Node<T>?
    
    init(value: T) {
        self.value = value
    }
}
117 chars
9 lines

Then, traverse the linked list until you reach the last node (i.e. a node where next property is nil):

main.swift
func append<T>(node: Node<T>, toLinkedList linkedList: Node<T>?) -> Node<T> {
    if linkedList == nil {
        return node
    }
    
    var current = linkedList
    while current?.next != nil {
        current = current?.next
    }
    
    current?.next = node
    return linkedList!
}
291 chars
14 lines

Finally, add the new node by setting the next property of the last node to the new node:

main.swift
let node1 = Node(value: 1)
let node2 = Node(value: 2)

let list = append(node: node1, toLinkedList: nil)
let newList = append(node: node2, toLinkedList: list)

// The linked list now contains nodes with values 1 and 2.
219 chars
8 lines

In the code above, append function is used to add a new node to the end of the linked list. The node argument is the node that you want to add to the end of the list, and the linkedList argument is the start node of the linked list. The append function returns the start node of the linked list with the new node added.

gistlibby LogSnag