Complete the code to define a struct for a singly linked list node with an integer value and a next pointer.
struct Node {
value: i32,
next: Option<Box<[1]>>,
}The next field must be an Option wrapping a Box pointing to the same Node type to allow recursive definition.
Complete the code to create a new node with value 10 and no next node.
let node = Node {
value: 10,
next: [1],
};The next pointer should be None to indicate the end of the list.
Fix the error in the code to link two nodes correctly.
let second = Node { value: 20, next: None };
let first = Node {
value: 10,
next: [1],
};The next field requires an Option. So we must box the second node and wrap it in Some.
Fill both blanks to implement a method that returns the value of the next node if it exists.
impl Node {
fn next_value(&self) -> Option<i32> {
self.next.as_ref().map(|[1]| *[2].value)
}
}The closure argument can be named anything, here n is used. Then we access *n.value to get the next node's value.
Fill all three blanks to implement a method that appends a new node with given value at the end of the list.
impl Node {
fn append(&mut self, val: i32) {
let mut current = self;
while let Some(ref mut [1]) = current.[2] {
current = [3];
}
current.next = Some(Box::new(Node { value: val, next: None }));
}
}We use next_node as the mutable reference name to the next node, access current.next, and then update current to next_node to traverse the list.
