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

To add a node to the beginning of a linked list in Swift, you first need to create a new node object with the data you want to add. Then, you can set the next property of your new node to the current head of the linked list. Finally, you set the head of the linked list to be the new node you just created.

Here is an example implementation of this approach in Swift:

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

class LinkedList<T> {
    var head: Node<T>?

    func addFirst(data: T) {
        let newNode = Node<T>()
        newNode.data = data
        newNode.next = head
        head = newNode
    }
}
253 chars
16 lines

In the code above, the addFirst function takes a parameter data of type T. It creates a new Node object which holds the data, sets the next property of the new node to the current head of the linked list, and finally sets the head of the linked list to be the new node.

You can then use this function to add nodes to the beginning of your linked list.

main.swift
let list = LinkedList<Int>()
list.addFirst(data: 1)
list.addFirst(data: 2)
list.addFirst(data: 3)
98 chars
5 lines

In the example above, we create a new empty linked list of integers. We then add three nodes to the beginning of the list with the values 3, 2, and 1, respectively. The resulting linked list will have a head of Node(data: 3) and the next node will be Node(data: 2), followed by Node(data: 1).

gistlibby LogSnag