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

To find the range of all nodes in a singly linked list in Rust, we can use iteration to traverse the list while keeping track of the minimum and maximum values.

Here's a possible implementation:

main.rs
use std::cmp::{max, min};

// Define the singly linked list node.
struct Node {
    val: i32,
    next: Option<Box<Node>>,
}

// Find the range of all nodes in the list.
fn find_range(head: Option<Box<Node>>) -> Option<(i32, i32)> {
    let mut min_val = i32::max_value();
    let mut max_val = i32::min_value();
    let mut current = head;

    while let Some(mut node) = current {
        // Update the min and max values.
        let val = node.val;
        min_val = min(min_val, val);
        max_val = max(max_val, val);

        // Move to the next node.
        current = node.next.take();
    }

    if min_val == i32::max_value() && max_val == i32::min_value() {
        // The list is empty.
        None
    } else {
        Some((min_val, max_val))
    }
}

// Example usage.
fn main() {
    // Create a linked list: 1 -> 3 -> -2 -> 4 -> 5
    let head = Some(Box::new(Node {
        val: 1,
        next: Some(Box::new(Node {
            val: 3,
            next: Some(Box::new(Node {
                val: -2,
                next: Some(Box::new(Node {
                    val: 4,
                    next: Some(Box::new(Node { val: 5, next: None })),
                })),
            })),
        })),
    }));

    // Find the range of all nodes.
    let range = find_range(head);
    if let Some((min_val, max_val)) = range {
        println!("Range: [{}, {}]", min_val, max_val);
    } else {
        println!("The list is empty.");
    }
}
1459 chars
58 lines

This program should output:

main.rs
Range: [-2, 5]
15 chars
2 lines

gistlibby LogSnag