find the largest node in a linked list in rust

To find the largest node in a linked list in Rust, you can iterate through the list and compare each node with the current maximum value. Here's an example implementation:

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

fn find_largest(head: Option<&Node>) -> i32 {
    let mut current = head;
    let mut max = std::i32::MIN;

    while let Some(node) = current {
        if node.value > max {
            max = node.value;
        }
        current = node.next.as_deref();
    }

    max
}
334 chars
19 lines

The Node struct represents a node in the linked list. It has a value field of type i32 and an optional next field that points to the next node in the list.

The find_largest function takes a reference to the head of the linked list and returns the value of the largest node in the list. It initializes a variable max to the minimum value of i32, and iterates through each element of the list using a while let loop, updating max as it encounters nodes with larger values.

Note that current is a mutable reference to the current node in the list, and as_deref is used to safely borrow a reference to the next node. This ensures that no ownership violations occur.

You can call find_largest with the head node of a linked list like this:

main.rs
let node5 = Node { value: 5, next: None };
let node4 = Node { value: 4, next: Some(Box::new(node5)) };
let node3 = Node { value: 3, next: Some(Box::new(node4)) };
let node2 = Node { value: 2, next: Some(Box::new(node3)) };
let node1 = Node { value: 1, next: Some(Box::new(node2)) };
let head = Some(&node1);

let largest = find_largest(head);
println!("The largest node value is {}", largest);
394 chars
10 lines

This creates a linked list with values 1, 2, 3, 4, and 5, and calls find_largest with the head node. The output will be:

main.rs
The largest node value is 5
28 chars
2 lines

gistlibby LogSnag