remove a node from the end of a linked list in swift

To remove the last node from a linked list in Swift, we need to traverse the entire list until we reach the second to last node, set its next property to nil, and delete the last node. Here is the code:

main.swift
func removeLast() {
    // If the list is empty, return
    guard var node = head else {
        return
    }
    // If there is only one node in the list, remove it
    if node.next == nil {
        head = nil
        return
    }
    // Traverse the list until we reach the second to last node
    while node.next?.next != nil {
        node = node.next!
    }
    // Set the second to last node's next property to nil
    node.next = nil
}
443 chars
18 lines

This code first checks if the list is empty, or if there is only one node in the list. If there are multiple nodes, it traverses the list until node.next.next is nil, indicating that node is the second to last node. Then, we set node.next to nil to remove the last node.

gistlibby LogSnag