find the smallest node in a linked list in rust

To find the smallest node in a linked list in Rust, we can traverse the linked list and keep track of the current minimum value.

Here's an implementation of this algorithm:

main.rs
struct Node {
    value: i32,
    next: Option<Box<Node>>, // singly linked list
}

impl Node {
    fn find_minimum(&self) -> i32 {
        if let Some(ref next) = self.next {
            // recursively find minimum in the rest of the list
            let rest_min = next.find_minimum();
            if self.value < rest_min {
                self.value
            } else {
                rest_min
            }
        } else {
            // base case: single node list
            self.value
        }
    }
}
515 chars
22 lines

We define a Node struct to represent a node in the linked list. The find_minimum method recursively finds the minimum value starting from the current node.

If the current node has a next node, we recursively call find_minimum on the next node and compare the minimum value in the rest of the list with the current node's value. We return the smaller of the two values.

If the current node doesn't have a next node, we've reached the end of the list and the node's value must be the smallest value in the list. We return the node's value as the base case.

To use this function, we call find_minimum on the first node of the linked list:

main.rs
let root = Node {
    value: 3,
    next: Some(Box::new(Node {
        value: 1,
        next: Some(Box::new(Node {
            value: 4,
            next: Some(Box::new(Node {
                value: 1, // minimum value
                next: None,
            })),
        })),
    })),
};

let min_val = root.find_minimum(); // returns 1
339 chars
16 lines

gistlibby LogSnag