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

To find the sum of all nodes in a linked list in Rust, we need to traverse the linked list and add up the values of each node.

First, we define the struct for the node of the linked list:

main.rs
struct Node {
    val: i32,
    next: Option<Box<Node>>,
}
59 chars
5 lines

Then, we create a function that takes the head of the linked list as input and returns the sum of all nodes:

main.rs
fn sum_linked_list(head: Option<Box<Node>>) -> i32 {
    let mut sum = 0;
    let mut curr = head;

    while let Some(node) = curr {
        sum += node.val;
        curr = node.next;
    }

    sum
}
202 chars
12 lines

In the above function, we initialize the sum to zero and set the current node to the head of the linked list. Then, we traverse the linked list with a while loop and add the value of each node to the sum. Finally, we return the sum.

Here is an example usage of the above function:

main.rs
fn main() {
    let mut head = Some(Box::new(Node{val: 1, next: None}));
    head = Some(Box::new(Node{val: 2, next: head}));
    head = Some(Box::new(Node{val: 3, next: head}));

    let sum = sum_linked_list(head);
    println!("Sum of nodes in linked list: {}", sum);
}
273 chars
9 lines

related categories

gistlibby LogSnag