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

To add a node to the end of a linked list in Rust, you can follow these steps:

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

impl Node {
    // function to append a new node at the end of the linked list
    fn append(&mut self, data: i32) {
        match &mut self.next {
            None => {
                self.next = Some(Box::new(Node { data, next: None }));
            }
            Some(node) => node.append(data),
        }
    }
}
379 chars
17 lines

In the above code, we define a Node struct to represent a node in the linked list. Each node contains a data field which holds the actual data of the node, and a next field which holds a pointer to the next node in the linked list. The next field is of type Option<Box<Node>>, meaning that it can either hold a Box<Node> (which is a way of dynamically allocating memory for the next node), or it can be empty (represented by None).

We then define an append function on the Node struct, which takes a mutable reference to self (i.e., the current node), as well as the data to be appended to the new node. The function recursively traverses the linked list until it finds the last node (i.e., the node whose next field is None), and then appends a new node with the given data to the next field of that node.

As an example, we can create a new linked list and append some nodes to it like so:

main.rs
fn main() {
    let mut head = Node {
        data: 1,
        next: None,
    };

    head.append(2);
    head.append(3);
    head.append(4);
}
145 chars
11 lines

This will create a linked list with four nodes containing the data 1, 2, 3, and 4, in that order.

gistlibby LogSnag