Append to Linked List

I have the following data structure:

pub struct Node<T: Clone> {
    value: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Node<T>
where
    T: Clone,
{
    fn new(value: T) -> Self {
        Node { value, next: None }
    }

    fn append(&mut self, value: T) {
        let next = Some(Box::new(Node { value, next: None }));
        if self.next.is_none() {
            self.next = next;
            return;
        }
        let mut temp = &mut self.next;
        while let Some(node) = temp {
            if node.next.is_some() {
                temp = &mut node.next;
            } else {
                break;
            }
        }
        // TODO: at this point, temp is the tail
    }
}

Notice the commend at the end of the append method. At this point, temp points to the tail, but since it's an Option<Box<Node<T>>>, I cannot access its next property. When I try to use as_mut() or replace() or some related method from Option, I get an error that temp is already borrowed mutably.

Any idea on how to modify the Node<T> within temp?

How does this Rust Playground look, as compared to what you want?

1 Like

Thanks, that's why I'm getting those ownership issues: node is the culprit—and the solution! :grinning:

Oh dear, I almost didn't dare to ask the question, because implementing linked lists in Rust is almost a cliche exercise. However, somebody else looking at it with fresh eyes can really help.

Thanks again!

It's also possible without the special case for the first node:

fn append(&mut self, value: T) {
    let mut next = &mut self.next;
    while let Some(node) = next {
        next = &mut node.next;
    }
    *next = Some(Box::new(Node { value, next: None }));
}
4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.