add a node to the beginning of a linked list in rust

To add a new node to the beginning of a linked list in Rust, you would first need to create a new node with the data you want to store. Then, you would need to update the next field of the new node to point to the current head of the linked list. Finally, you would set the new node as the new head of the linked list. Here's how you can do it:

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 }
    }
}

fn add_to_beginning<T>(head: Option<Box<Node<T>>>, data: T) -> Option<Box<Node<T>>> {
    let new_node = Box::new(Node::new(data));
    new_node.next = head; // Set next field to point to current head
    
    Some(new_node) // Set the new node as the new head of the linked list
}
438 chars
18 lines

In this example, the add_to_beginning function takes in the current head of the linked list and the data for the new node. It returns an Option<Box<Node<T>>>, where the Box<Node<T>> is the new head of the linked list.

To use this function, you can create a new linked list with a single node like this:

main.rs
let head = Some(Box::new(Node::new(1)));
41 chars
2 lines

Then, you can add a new node to the beginning of the linked list like this:

main.rs
let new_head = add_to_beginning(head, 2);
42 chars
2 lines

The new_head variable now contains the new head of the linked list, with a data value of 2 and a next field pointing to the previous head (with a data value of 1).

gistlibby LogSnag