What is the main structural difference between a circular linked list and a linear linked list?
Think about where the last node points in each list type.
The key difference is that in a circular linked list, the last node's next pointer points back to the first node, forming a loop. In a linear linked list, the last node points to null, marking the end.
Consider a circular linked list with nodes containing values 1, 2, 3 linked in order. What will be the output of traversing the list starting from the head and stopping after visiting 3 nodes?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
let node3 = Node { value: 3, next: None };
let node2 = Node { value: 2, next: Some(Box::new(node3)) };
let mut node1 = Node { value: 1, next: Some(Box::new(node2)) };
// Making it circular
if let Some(ref mut n3) = node1.next.as_mut().unwrap().next {
n3.next = Some(Box::new(node1));
}
// Traverse 3 nodes starting from node1
let mut current = &node1;
for _ in 0..3 {
print!("{} -> ", current.value);
current = current.next.as_ref().unwrap();
}
print!("null");
}Traversal stops after visiting exactly 3 nodes.
Even though the list is circular, the traversal stops after 3 nodes, so it prints 1, 2, 3 and then 'null' to indicate stopping.
Given the following Rust code for a linear linked list, why does the traversal cause a runtime error?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
let node3 = Node { value: 3, next: None };
let node2 = Node { value: 2, next: Some(Box::new(node3)) };
let node1 = Node { value: 1, next: Some(Box::new(node2)) };
let mut current = &node1;
loop {
println!("{}", current.value);
current = current.next.as_ref().unwrap();
}
}Think about what happens when current.next is None.
The loop does not check if current.next is None before calling unwrap(), so when it reaches the last node, unwrap() on None causes a panic (runtime error).
Which option contains a syntax error when trying to create a circular linked list in Rust?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
// Code snippets below
}Check if variables are mutable when modified.
Option A tries to assign to node1.next but node1 is not mutable, causing a syntax error.
Starting with a circular linked list of 3 nodes (values 1, 2, 3), a new node with value 4 is inserted after node 3. How many nodes does the list have now?
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
// Initial circular list: 1 -> 2 -> 3 -> back to 1
// Insert node 4 after node 3
}Inserting a node adds one node to the list.
Inserting a new node after node 3 adds one node to the existing 3 nodes, making total 4 nodes.
