Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a linked list is circular by comparing the next pointer of the last node.
DSA Rust
if last_node.next == [1] { println!("The list is circular"); } else { println!("The list is linear"); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using None instead of head to check circularity.
✗ Incorrect
In a circular linked list, the last node's next points back to the head node.
2fill in blank
mediumComplete the code to traverse a linear linked list until the end (None).
DSA Rust
while let Some(node) = current { println!("{}", node.value); current = node.[1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' or 'head' instead of 'next' to traverse.
✗ Incorrect
To move forward in a linked list, we follow the next pointer of the current node.
3fill in blank
hardFix the error in the code that tries to detect circular linked list by comparing nodes.
DSA Rust
fn is_circular(head: Option<Box<Node>>) -> bool {
let mut slow = &head;
let mut fast = &head;
while fast.is_some() && fast.as_ref().unwrap().next.is_some() {
slow = &slow.as_ref().unwrap().next;
fast = &fast.as_ref().unwrap().next.as_ref().unwrap().[1];
if slow == fast {
return true;
}
}
false
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' or 'head' instead of 'next' for fast pointer.
✗ Incorrect
The fast pointer moves two steps ahead by following 'next' twice to detect cycles.
4fill in blank
hardFill both blanks to create a function that returns the last node's next pointer in a linked list.
DSA Rust
fn get_last_next(mut node: &Option<Box<Node>>) -> Option<&Option<Box<Node>>> {
while node.as_ref().unwrap().[1].is_some() {
node = &node.as_ref().unwrap().[2];
}
Some(&node.as_ref().unwrap().next)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' or 'head' instead of 'next' to traverse.
✗ Incorrect
To find the last node, keep moving through 'next' until it is None.
5fill in blank
hardFill all three blanks to create a function that builds a circular linked list from a vector of values.
DSA Rust
fn build_circular_list(values: Vec<i32>) -> Option<Box<Node>> {
let mut head = None;
let mut tail = None;
for val in values {
let new_node = Box::new(Node { value: val, next: None });
if head.is_none() {
head = Some(new_node);
tail = head.as_mut();
} else {
tail.unwrap().[1] = Some(new_node);
tail = tail.unwrap().[2].as_mut();
}
}
if let Some(t) = tail {
t.[3] = head.clone();
}
head
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' to link nodes.
Not linking last node to head.
✗ Incorrect
We link nodes using 'next', and finally point the last node's 'next' to head to make it circular.
