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

Here's one way to find the mode of all nodes in a linked list in Rust:

main.rs
use std::collections::HashMap;

// Define a node struct for the linked list
struct Node {
    value: i32,
    next: Option<Box<Node>>,
}

impl Node {
    fn new(v: i32) -> Self {
        Self { value: v, next: None }
    }
}

fn mode_of_linked_list(head: Option<Box<Node>>) -> Option<i32> {
    if head.is_none() {
        return None;
    }

    let mut map = HashMap::new();

    // Traverse the linked list and count occurrences of each value
    let mut cur = head;
    while let Some(node) = cur {
        let count = map.entry(node.value).or_insert(0);
        *count += 1;
        cur = node.next;
    }

    // Find the mode value
    let mut mode = None;
    let mut max_count = 0;
    for (value, count) in map {
        if count > max_count {
            mode = Some(value);
            max_count = count;
        }
    }

    mode
}

// Example usage
fn main() {
    let n1 = Node::new(1);
    let n2 = Node::new(2);
    let n3 = Node::new(3);
    let n4 = Node::new(2);

    n1.next = Some(Box::new(n2));
    n2.next = Some(Box::new(n3));
    n3.next = Some(Box::new(n4));

    let mode = mode_of_linked_list(Some(Box::new(n1)));
    println!("Mode of linked list is {:?}", mode); // Mode of linked list is Some(2)
}
1230 chars
57 lines

The mode_of_linked_list function takes the head of the linked list as input and returns an Option<i32> representing the mode value. It first creates a HashMap to count the occurrences of each value in the linked list. Then, it finds the value with the highest count and returns it as the mode. If multiple values have the same highest count, it returns the first one encountered.

gistlibby LogSnag