find the range of all nodes in a linked list in go

To find the range of all nodes in a linked list in Go, you can follow the below algorithm -

  1. Traverse the linked list from the head node to the tail node.
  2. Maintain two variables - min and max, initialized to the value of the first node.
  3. Compare the value of each subsequent node with min and max.
  4. If the value is less than min, update min.
  5. If the value is greater than max, update max.
  6. After traversing the entire linked list, the range would be [min, max].

Here is the implementation:

main.go
type Node struct {
    data int
    next *Node
}

func findRange(head *Node) (int, int) {
    if head == nil {
        return 0, 0
    }
    min, max := head.data, head.data
    current := head.next
    for current != nil {
        if current.data < min {
            min = current.data
        } else if current.data > max {
            max = current.data
        }
        current = current.next
    }
    return min, max
}
426 chars
22 lines

In the above implementation, we traverse the linked list starting from the head node. We compare the value of each node with min and max, and update the values accordingly. Finally, we return the range (min, max).

You can call this function with the head of the linked list to find the range of all nodes.

gistlibby LogSnag