Complete the code to define the Node struct with a value and a next pointer.
struct Node<T> {
value: T,
next: [1],
}The next pointer should be an Option wrapping a Box to allow for nullable and heap allocation.
Complete the code to create a new Node with given value and no next node.
impl<T> Node<T> {
fn new(value: T) -> Self {
Node {
value,
next: [1],
}
}
}The next pointer should be None when creating a new node with no next node.
Fix the error in the push method to add a new node at the front of the list.
impl<T> LinkedList<T> {
fn push(&mut self, value: T) {
let mut new_node = Box::new(Node::new(value));
new_node.next = [1];
self.head = Some(new_node);
}
}To insert at the front, the new node's next should point to the current head.
Fill both blanks to implement a method that checks if the list is empty.
impl<T> LinkedList<T> {
fn is_empty(&self) -> bool {
self.head [1] [2]
}
}The list is empty if head is equal to None.
Fill all three blanks to implement a method that counts nodes in the list.
impl<T> LinkedList<T> {
fn length(&self) -> usize {
let mut count = 0;
let mut current = &self.head;
while let [1]([3]) = current {
count += 1;
current = &[2];
}
count
}
}The while let Some(node) pattern unwraps the current node. Then we move to node.next to continue. The variable node holds the current node.
