# find the range of all nodes in a linked list in swift

Assuming that the linked list contains nodes with integer values, we can find the range of all nodes in the linked list using the following algorithm:

1. Initialize two variables, `min` and `max`, both to the value of the first node in the list.
2. Traverse the linked list, and for each node: a. If the value of the node is less than `min`, update `min` to the value of the node. b. If the value of the node is greater than `max`, update `max` to the value of the node.
3. Once all nodes have been traversed, the range of all nodes in the linked list is the difference between `max` and `min`.

Here is an implementation of this algorithm in Swift:

```main.swift```func findRangeOfNodes(in list: LinkedList<Int>) -> Int? {
guard let firstNode = list.head else {
return nil // the list is empty
}
var min = firstNode.value
var max = firstNode.value
var currentNode = firstNode.next
while let node = currentNode {
if node.value < min {
min = node.value
}
if node.value > max {
max = node.value
}
currentNode = node.next
}
return max - min
}
```478 chars19 lines```

This function takes a `LinkedList<Int>` as input, and returns the range of all nodes in the list as an `Int`. If the list is empty, it returns `nil`.

### related categories

gistlibby LogSnag