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 in a linked list node is an optional Box pointing to the next Node.
Complete the push method to add a new node at the top of the stack.
impl<T> Stack<T> {
fn push(&mut self, value: T) {
let new_node = Box::new(Node {
value,
next: [1],
});
self.top = Some(new_node);
}
}We take ownership of the current top node to link it as next of the new node.
Fix the error in the pop method to correctly remove and return the top value.
impl<T> Stack<T> {
fn pop(&mut self) -> Option<T> {
self.top.take().map(|node| {
self.top = [1];
node.value
})
}
}After taking the top node, set self.top to node.next to update the stack.
Fill both blanks to implement the peek method returning a reference to the top value.
impl<T> Stack<T> {
fn peek(&self) -> Option<&T> {
self.top.as_ref().map(|node| [1])
}
fn peek_mut(&mut self) -> Option<&mut T> {
self.top.as_mut().map(|node| [2])
}
}peek returns a reference, so use &node.value; peek_mut returns mutable reference, so use &mut node.value.
Fill all three blanks to implement the is_empty method and a new Stack constructor.
impl<T> Stack<T> {
fn new() -> Self {
Stack { top: [1] }
}
fn is_empty(&self) -> bool {
self.top [2] None
}
fn size(&self) -> usize {
let mut count = 0;
let mut current = self.top.as_ref();
while let Some(node) = current {
count += 1;
current = node.[3];
}
count
}
}new initializes top as None; is_empty checks if top == None; size traverses nodes using next.as_ref().
