Bird
Raised Fist0
DSA Rustprogramming~10 mins

Insert at Beginning of Circular Linked List in DSA Rust - Execution Trace

Choose your learning style10 modes available
Concept Flow - Insert at Beginning of Circular Linked List
Create new node
↓
Is list empty?
Yes→new_node.next = new_node
|No↓
Find last node (node.next == head)
↓
new_node.next = head
↓
last_node.next = new_node
↓
head = new_node
↓
Done
Create a new node, link it to the current head, update the last node to point to new node, then update head to new node.
Execution Sample
DSA Rust
fn insert_at_beginning(head: Option<Box<Node>>, data: i32) -> Option<Box<Node>> {
    let mut new_node = Box::new(Node { data, next: None });
    if head.is_none() {
        new_node.next = Some(new_node.clone());
        return Some(new_node);
    }
    // Find last node and update pointers
    // Update head to new_node
}
This function inserts a new node at the beginning of a circular linked list, updating pointers accordingly.
Execution Table
StepOperationNodes in ListPointer ChangesVisual State
1Create new node with data=10Emptynew_node.next = Noneāˆ…
2Check if list is emptyEmptyhead = Noneāˆ…
3List empty: new_node.next points to itself1 nodenew_node.next → new_nodeā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:10│ │ next:──┼──→ (points to self) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ head
4Return new_node as head1 nodehead = new_nodeā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:10│ │ next:──┼──→ (points to self) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ head
5Insert new node with data=20 at beginning (list not empty)1 nodenew_node.next = headBefore: ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:10│ │ next:──┼──→ (points to self) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ head After new_node.next = head: ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:20│ │ data:10│ │ next:──┼──→ │ next:──┼──→ (points to self) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
6Find last node (node.next == head)1 nodeTraverse from head to find last nodeCurrent node: data=10 (last node)
7Update last_node.next to new_node2 nodeslast_node.next → new_nodeā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:20│ │ data:10│ │ next:──┼──→ │ next:──┼──→ (points to new_node) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ head
8Update head to new_node2 nodeshead = new_nodeā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ data:20│ │ data:10│ │ next:──┼──→ │ next:──┼──→ (points to head) ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ head
9Done2 nodesPointers updated correctlyCircular list: 20 → 10 → (back to 20)
šŸ’” Insertion complete, head updated, list remains circular
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7Final
headNoneNode(10)Node(10)Node(10)Node(20)
new_nodeNoneNode(10)Node(20)Node(20)Node(20)
last_nodeNoneNoneNoneNode(10)Node(10)
Key Moments - 3 Insights
Why does the new node point to itself when the list is empty?
Because in a circular linked list with one node, that node's next pointer must point to itself to maintain the circular structure. See execution_table step 3.
How do we find the last node in the circular list?
We traverse nodes starting from head until we find a node whose next points back to head. This is shown in execution_table step 6.
Why do we update last_node.next to new_node before changing head?
To keep the list circular, the last node must point to the new head. Updating last_node.next first ensures no break in the circle. See execution_table step 7 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does new_node.next point to after step 3?
AIt points to None
BIt points to itself
CIt points to head
DIt points to last_node
šŸ’” Hint
Check execution_table row for step 3 under Pointer Changes
At which step does the last node's next pointer get updated to point to the new node?
AStep 5
BStep 6
CStep 7
DStep 8
šŸ’” Hint
Look at execution_table Pointer Changes column for when last_node.next changes
If the list was initially empty, what would be the final head node's data after insertion?
A10
BNone
C20
DDepends on last_node
šŸ’” Hint
Refer to variable_tracker for head after step 3 when list was empty
Concept Snapshot
Insert at Beginning of Circular Linked List:
- Create new node
- If list empty: new_node.next = new_node (points to self)
- Else find last node (node.next == head)
- Set new_node.next = head
- Set last_node.next = new_node
- Update head = new_node
- List remains circular after insertion
Full Transcript
To insert at the beginning of a circular linked list, first create a new node. If the list is empty, point the new node's next to itself and set it as head. If not empty, find the last node whose next points to head. Then set new_node.next to current head, update last_node.next to new_node, and finally update head to new_node. This keeps the list circular and inserts the new node at the start.

Practice

(1/5)
1. What happens when you insert a new node at the beginning of a circular linked list?
easy
A. The new node is added at the end and does not affect the head.
B. The new node replaces the last node in the list.
C. The list breaks and becomes a linear linked list.
D. The new node becomes the head and points to the old head, maintaining the circular link.

Solution

  1. Step 1: Understand circular linked list structure

    In a circular linked list, the last node points back to the head node, forming a circle.
  2. Step 2: Insert new node at beginning

    The new node is linked to the current head, and the last node's next pointer is updated to this new node, making it the new head.
  3. Final Answer:

    The new node becomes the head and points to the old head, maintaining the circular link. -> Option D
  4. Quick Check:

    New head points to old head, circle intact [OK]
Hint: New head points to old head; last node links to new head [OK]
Common Mistakes:
  • Forgetting to update last node's next pointer
  • Breaking the circular link accidentally
  • Replacing the last node instead of adding new head
2. Which Rust code snippet correctly creates a new node and inserts it at the beginning of a circular linked list?
easy
A. let new_node = Node { data: val, next: head.clone() }; last.next = Some(new_node.clone()); head = Some(new_node);
B. let new_node = Node { data: val, next: None }; head = Some(new_node);
C. let new_node = Node { data: val, next: last.clone() }; head = Some(new_node);
D. let new_node = Node { data: val, next: head.clone() }; head = Some(new_node);

Solution

  1. Step 1: Create new node pointing to current head

    The new node's next pointer should point to the current head to maintain the list.
  2. Step 2: Update last node's next to new node and update head

    Since it's circular, last node's next must point to new node, then head is updated to new node.
  3. Final Answer:

    let new_node = Node { data: val, next: head.clone() }; last.next = Some(new_node.clone()); head = Some(new_node); -> Option A
  4. Quick Check:

    New node next = head, last next = new node, head updated [OK]
Hint: New node next = head; last.next updated; head = new node [OK]
Common Mistakes:
  • Not updating last node's next pointer
  • Setting new node's next to None
  • Not cloning nodes properly causing ownership errors
3. Given the following Rust code for inserting at the beginning of a circular linked list, what will be the printed list after insertion?
struct Node {
    data: i32,
    next: Option,
}

fn print_list(head: &Option) {
    if head.is_none() { return; }
    let mut temp = head.as_ref();
    loop {
        if let Some(node) = temp {
            print!("{} -> ", node.data);
            temp = node.next.as_ref();
            if temp == head.as_ref() { break; }
        }
    }
    println!("null");
}

fn insert_beginning(head: &mut Option, val: i32) {
    let mut new_node = Box::new(Node { data: val, next: None });
    if head.is_none() {
        new_node.next = Some(new_node.clone());
        *head = Some(new_node);
        return;
    }
    let mut temp = head.as_mut().unwrap();
    while temp.next.as_ref().unwrap().as_ref() != head.as_ref().unwrap().as_ref() {
        temp = temp.next.as_mut().unwrap();
    }
    new_node.next = head.take();
    temp.next = Some(new_node);
    *head = temp.next.clone();
}

fn main() {
    let mut head = None;
    insert_beginning(&mut head, 10);
    insert_beginning(&mut head, 20);
    insert_beginning(&mut head, 30);
    print_list(&head);
}
medium
A. 30 -> 10 -> 20 -> null
B. 30 -> 20 -> 10 -> null
C. 10 -> 20 -> 30 -> null
D. 20 -> 30 -> 10 -> null

Solution

  1. Step 1: Trace insertions in order

    Insert 10 first: list is 10 -> 10 (single node points to itself). Insert 20: new node 20 points to 10, last node (10) points to 20, head updated to 20. Insert 30: new node 30 points to 20, last node (10) points to 30, head updated to 30.
  2. Step 2: Print list starting from head

    Starting at 30, next is 20, then 10, then back to 30 (stop). So printed: 30 -> 20 -> 10 -> null.
  3. Final Answer:

    30 -> 20 -> 10 -> null -> Option B
  4. Quick Check:

    New nodes inserted at head, order reversed [OK]
Hint: New insertions become head, list order reverses [OK]
Common Mistakes:
  • Confusing order of nodes after insertion
  • Not updating last node's next pointer correctly
  • Incorrect loop condition in print function
4. Identify the bug in this Rust function that inserts a node at the beginning of a circular linked list:
fn insert_beginning(head: &mut Option, val: i32) {
    let mut new_node = Box::new(Node { data: val, next: None });
    if head.is_none() {
        new_node.next = Some(new_node.clone());
        *head = Some(new_node);
        return;
    }
    let mut temp = head.as_mut().unwrap();
    while temp.next.as_ref().unwrap().as_ref() != head.as_ref().unwrap().as_ref() {
        temp = temp.next.as_mut().unwrap();
    }
    new_node.next = head.take();
    temp.next = Some(new_node);
    *head = temp.next.clone();
}
medium
A. head.take() removes the list causing loss of nodes.
B. The while loop condition never terminates causing infinite loop.
C. Cloning new_node causes infinite recursion and stack overflow.
D. temp.next is not updated correctly to point to new_node.

Solution

  1. Step 1: Analyze cloning of new_node

    Cloning new_node inside new_node.next = Some(new_node.clone()) causes recursive cloning because new_node contains next which contains new_node again, leading to infinite recursion.
  2. Step 2: Understand Rust cloning behavior

    Rust's clone on a Box<Node> will recursively clone the entire structure, so cloning a node that points to itself causes stack overflow.
  3. Final Answer:

    Cloning new_node causes infinite recursion and stack overflow. -> Option C
  4. Quick Check:

    Self-referential clone causes infinite recursion [OK]
Hint: Avoid cloning self-referential nodes to prevent recursion [OK]
Common Mistakes:
  • Ignoring cloning impact on self-referential structures
  • Assuming head.take() deletes nodes permanently
  • Misreading loop condition as infinite
5. You want to insert a new node at the beginning of a circular linked list that may be empty or non-empty. Which approach correctly handles both cases in Rust without cloning self-referential nodes?
fn insert_beginning(head: &mut Option, val: i32) {
    let mut new_node = Box::new(Node { data: val, next: None });
    if head.is_none() {
        // Case 1: Empty list
        new_node.next = Some(new_node); // Problem here
        *head = Some(new_node);
        return;
    }
    // Case 2: Non-empty list
    let mut temp = head.as_mut().unwrap();
    while temp.next.as_ref().unwrap().as_ref() != head.as_ref().unwrap().as_ref() {
        temp = temp.next.as_mut().unwrap();
    }
    new_node.next = head.take();
    temp.next = Some(new_node);
    *head = temp.next.clone();
}
What is the correct fix for Case 1 to avoid cloning and infinite recursion?
hard
A. Use a raw pointer or Rc to create self-reference safely.
B. Set new_node.next = None and update last node later.
C. Create a temporary node and assign new_node.next to it.
D. Use unsafe code to manually set new_node.next to itself.

Solution

  1. Step 1: Understand self-referential node problem

    Assigning new_node.next = Some(new_node) tries to move new_node into itself, which is invalid and causes infinite recursion if cloned.
  2. Step 2: Use Rc or raw pointers

    Rust's safe way to handle self-references is using Rc (reference counting) and RefCell (interior mutability) to create cyclic references without cloning issues.
  3. Step 3: Avoid unsafe code unless necessary

    Using unsafe code is error-prone; Rc<RefCell> is the recommended safe approach.
  4. Final Answer:

    Use a raw pointer or Rc to create self-reference safely. -> Option A
  5. Quick Check:

    Safe self-reference needs Rc/RefCell or raw pointers [OK]
Hint: Use Rc<RefCell> for safe self-referential nodes [OK]
Common Mistakes:
  • Assigning node to itself directly causing move errors
  • Using None breaks circular property
  • Using unsafe code without understanding risks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard