find the first node in a linked list in rust

To find the first node in a linked list in Rust, you first need to have a struct for your linked list node which has a next field to point to the next node in the list. Here's an example implementation:

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

impl<T> Node<T> {
    fn new(data: T) -> Self {
        Node { data, next: None }
    }
}
155 chars
11 lines

Once you have your linked list nodes set up, you can create a new node by calling Node::new(data) and append nodes to your list by setting the next field to the next node you create. Finally, to find the first node in the list, you can simply access the head of the list using its pointer. Here's an example implementation of a find_first_node() function that returns an immutable reference to the first node:

main.rs
fn find_first_node<T>(head: &Node<T>) -> &Node<T> {
    head
}
63 chars
4 lines

This function simply returns a reference to the head of the list, which is the first node in the list. You can then use this reference to access the data in the first node.

Here's an example usage:

main.rs
fn main() {
    let mut head = Node::new("Hello");
    head.next = Some(Box::new(Node::new("World")));
    let first_node = find_first_node(&head);
    println!("{}", first_node.data); // prints "Hello"
}
205 chars
7 lines

gistlibby LogSnag