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

To remove a node from the middle of a linked list, we first need to identify the node that we want to remove. Once identified, we can rearrange the links of the surrounding nodes to remove the desired node from the list.

Assuming we have a singly linked list implementation with a Node class as follows:

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

We can implement a method to remove a node from the middle of the linked list as follows:

main.swift
func removeNodeFromMiddle<T>(_ head: Node<T>?, _ nodeToRemove: Node<T>) -> Node<T>? {
    guard head != nil else { return nil } // empty list
    guard nodeToRemove !== head else { return head?.next } // remove head node
    
    var prev: Node<T>?
    var current = head
    
    while current != nil && current !== nodeToRemove {
        prev = current
        current = current?.next
    }
    
    prev?.next = current?.next // remove node by skipping it in the linked list
    nodeToRemove.next = nil // optional: clear next reference to indicate the node is no longer part of list
    
    return head
}
610 chars
18 lines

In the above method, we first handle the case of an empty list or removing the head node. We then iterate through the linked list until we find the node to remove. Once found, we remove it from the list by updating the next reference of the previous node to skip over the node to remove.

Note that in the implementation, we assume that the node to remove is actually part of the linked list. If not, the above method will not work as expected.

gistlibby LogSnag