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

To find the median of all nodes in a linked list in Rust, we can follow the following steps:

  1. Traverse the linked list and store all the values in a vector.
  2. Sort the vector.
  3. If the length of the vector is odd, return the middle element. If the length is even, return the average of the middle two elements.

Here's the code:

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

fn main() {
    let mut list = LinkedList::new();
    list.push_back(1);
    list.push_back(4);
    list.push_back(2);
    list.push_back(3);
    list.push_back(5);

    let mut values = Vec::new();
    for value in list {
        values.push(value);
    }
    values.sort();

    let length = values.len();
    let median = if length % 2 == 0 {
        (values[length / 2 - 1] + values[length / 2]) as f32 / 2.0
    } else {
        values[length / 2] as f32
    };
    println!("Median of linked list: {}", median);
}
555 chars
25 lines

In this code, we first create a linked list and add some values to it. Then we traverse the list and store all the values in a vector. We sort the vector and find the median as described above. Finally, we print the median value.

gistlibby LogSnag