find the last node in a linked list in rust

main.rs
struct ListNode {
    val: i32,
    next: Option<Box<ListNode>>,
}

impl Solution {
    fn get_last_node(head: Option<Box<ListNode>>) -> Option<i32> {
        let mut current_node = head;
        while let Some(node) = current_node {
            if node.next.is_none() {
                return Some(node.val);
            }
            current_node = node.next;
        }
        None
    }
}
393 chars
18 lines

The above code defines a struct for a ListNode where each node has a value val and a pointer next to the next element in the list. fn get_last_node takes an input argument head which is the first element of the linked list. We start from the head and traverse through the list until we reach an element whose next pointer is empty i.e. None. Finally, the value of the last node is returned using the Some enum in Rust. If there are no elements in the linked list, then it returns None.

gistlibby LogSnag