Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new node with given data.
DSA Rust
struct Node {
data: i32,
next: Option<Box<Node>>,
}
impl Node {
fn new(data: i32) -> Self {
Node { data: [1], next: None }
}
}Attempts:
3 left
š” Hint
Common Mistakes
Assigning None or Box::new(data) instead of the data value.
Using a literal like 0 instead of the parameter.
ā Incorrect
The new node should store the given data value in its data field.
2fill in blank
mediumComplete the code to link the new node to itself to form a circular list.
DSA Rust
fn create_circular_node(data: i32) -> Box<Node> {
let mut node = Box::new(Node::new(data));
node.next = Some([1]);
node
}Attempts:
3 left
š” Hint
Common Mistakes
Creating a new node instead of pointing to the existing one.
Assigning None which breaks the circular link.
ā Incorrect
To make the list circular, the node's next should point to itself.
3fill in blank
hardFix the error in the method to insert a new node after the head in the circular list.
DSA Rust
impl Node {
fn insert_after(&mut self, data: i32) {
let mut new_node = Box::new(Node::new(data));
new_node.next = self.next.take();
self.next = Some([1]);
}
}Attempts:
3 left
š” Hint
Common Mistakes
Assigning self or a new node instead of the created new_node.
Using unwrap() which may panic if next is None.
ā Incorrect
The new_node must be linked after self, so self.next points to new_node.
4fill in blank
hardFill both blanks to traverse the circular list and print each node's data once.
DSA Rust
fn print_circular_list(head: &Node) {
let mut current = head;
loop {
println!("{}", current.data);
current = current.next.as_ref().map(|node| &**node).unwrap();
if current.data [1] head.data {
break;
}
}
}Attempts:
3 left
š” Hint
Common Mistakes
Using '!=' causes infinite loop.
Using comparison operators like '<' or '>' which are incorrect here.
ā Incorrect
Stop when current's data equals head's data to avoid infinite loop.
5fill in blank
hardFill all three blanks to implement a method that deletes the node after the current node in the circular list.
DSA Rust
impl Node {
fn delete_after(&mut self) {
if let Some(mut next_node) = self.next.take() {
self.next = next_node.next.take();
next_node.next = None; // disconnect deleted node
}
}
fn delete_after_fixed(&mut self) {
if let Some(mut next_node) = self.next.take() {
self.next = next_node.[1].take();
next_node.[2] = [3]; // disconnect deleted node
}
}
}Attempts:
3 left
š” Hint
Common Mistakes
Using wrong field names like 'data' instead of 'next'.
Not setting the disconnected node's next to None.
ā Incorrect
To delete the node after self, assign self.next to next_node.next.take(), then disconnect next_node.next by setting it to None.
