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

To find the average of all nodes in a linked list in Rust, we need to iterate through the entire linked list and sum up the values of all nodes. Then, we can divide the sum by the number of nodes in the linked list to get the average.

Here's some sample code that demonstrates how to do this:

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

impl Node {
    fn new(data: i32) -> Node {
        Node { data, next: None }
    }
    
    fn append(&mut self, data: i32) {
        let mut current_node = self;
        while let Some(ref mut boxed_node) = current_node.next {
            current_node = boxed_node;
        }
        current_node.next = Some(Box::new(Node::new(data)));
    }
}

fn find_average(head: Option<Box<Node>>) -> f32 {
    let mut sum = 0;
    let mut count = 0;

    let mut current_node = head;
    while let Some(boxed_node) = current_node {
        sum += boxed_node.data;
        count += 1;
        current_node = boxed_node.next;
    }

    if count == 0 {
        return 0.0;
    }

    sum as f32 / count as f32
}

fn main() {
    let mut list = Node::new(1);
    list.append(2);
    list.append(3);
    
    let average = find_average(Some(Box::new(list)));

    println!("The average of all nodes in the linked list is: {}", average);
}
988 chars
47 lines

In this code, we define a Node struct that represents a node in the linked list. Each node contains some data as well as a reference to the next node in the list.

The find_average function takes the head of the linked list as an argument (which is an Option<Box<Node>>). It iterates through the linked list using a while let loop and sums up the value of the data in each node, as well as counts the number of nodes in the list. Then, it returns the average of all node data in the form of a floating-point number.

In the main function, we create a linked list with three nodes (1 -> 2 -> 3) and call the find_average function to find the average of all nodes in the list. The output will be The average of all nodes in the linked list is: 2.

gistlibby LogSnag