Consider a singly linked list with nodes containing values 10 -> 20 -> 30 -> null. After popping the head node, what is the printed state of the list?
struct Node {
val: i32,
next: Option<Box<Node>>,
}
fn pop_head(mut head: Option<Box<Node>>) -> Option<Box<Node>> {
if head.is_none() {
return None;
}
head.unwrap().next
}
fn print_list(head: &Option<Box<Node>>) {
let mut current = head;
while let Some(node) = current {
print!("{} -> ", node.val);
current = &node.next;
}
println!("null");
}
fn main() {
let third = Box::new(Node { val: 30, next: None });
let second = Box::new(Node { val: 20, next: Some(third) });
let first = Box::new(Node { val: 10, next: Some(second) });
let head = Some(first);
let new_head = pop_head(head);
print_list(&new_head);
}Pop removes the first node, so the new head is the second node.
After popping, the head node with value 10 is removed. The new head points to the node with value 20, followed by 30, then null.
Given an empty linked list (head is None), what is the output after calling pop_head and then printing the list?
struct Node {
val: i32,
next: Option<Box<Node>>,
}
fn pop_head(mut head: Option<Box<Node>>) -> Option<Box<Node>> {
if head.is_none() {
return None;
}
head.unwrap().next
}
fn print_list(head: &Option<Box<Node>>) {
let mut current = head;
while let Some(node) = current {
print!("{} -> ", node.val);
current = &node.next;
}
println!("null");
}
fn main() {
let head: Option<Box<Node>> = None;
let new_head = pop_head(head);
print_list(&new_head);
}Check if the list is empty before popping.
Since the list is empty, pop_head returns None. Printing the list shows just null.
Identify the cause of panic in this pop_head function when called on a non-empty list.
fn pop_head(mut head: Option<Box<Node>>) -> Option<Box<Node>> {
let next_node = head.unwrap().next;
head = None;
next_node
}Consider ownership and moves when calling unwrap.
Calling unwrap() moves the Box
Given a linked list 5 -> 15 -> 25 -> null, what is the printed list after calling pop_head twice?
struct Node {
val: i32,
next: Option<Box<Node>>,
}
fn pop_head(mut head: Option<Box<Node>>) -> Option<Box<Node>> {
if head.is_none() {
return None;
}
head.unwrap().next
}
fn print_list(head: &Option<Box<Node>>) {
let mut current = head;
while let Some(node) = current {
print!("{} -> ", node.val);
current = &node.next;
}
println!("null");
}
fn main() {
let third = Box::new(Node { val: 25, next: None });
let second = Box::new(Node { val: 15, next: Some(third) });
let first = Box::new(Node { val: 5, next: Some(second) });
let head = Some(first);
let head_after_first_pop = pop_head(head);
let head_after_second_pop = pop_head(head_after_first_pop);
print_list(&head_after_second_pop);
}Each pop removes the current head node.
First pop removes 5, second pop removes 15, leaving 25 -> null.
Choose the best explanation for why linked list nodes are wrapped in Option
Think about how Rust handles ownership and absence of values.
Option
