Bird
Raised Fist0
DSA Rustprogramming

Insert at Middle Specific Position in DSA Rust

Choose your learning style10 modes available
Mental Model
We add a new item inside a list exactly where we want, pushing others after it.
Analogy: Imagine a line of people holding hands. To add a new friend in the middle, you gently let go and hold the new friend's hand, then the new friend holds the next person's hand.
1 -> 2 -> 3 -> 4 -> null
          ↑ insert here at position 3
Dry Run Walkthrough
Input: list: 1 -> 2 -> 4 -> 5, insert value 3 at position 3
Goal: Insert the value 3 exactly between 2 and 4, so the list becomes 1 -> 2 -> 3 -> 4 -> 5
Step 1: start at head node with value 1
1 [curr->1] -> 2 -> 4 -> 5 -> null
Why: We begin from the start to find the right place to insert
Step 2: move curr to next node with value 2
1 -> 2 [curr->2] -> 4 -> 5 -> null
Why: We move forward to reach the node before the insertion point
Step 3: create new node with value 3 and link it after curr
1 -> 2 -> 3 [new] -> 4 -> 5 -> null
Why: Insert new node by adjusting pointers to place it between 2 and 4
Result:
1 -> 2 -> 3 -> 4 -> 5 -> null
Annotated Code
DSA Rust
use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug, Clone)]
struct Node {
    val: i32,
    next: Option<Rc<RefCell<Node>>>,
}

impl Node {
    fn new(val: i32) -> Rc<RefCell<Node>> {
        Rc::new(RefCell::new(Node { val, next: None }))
    }
}

fn insert_at_position(head: Option<Rc<RefCell<Node>>>, val: i32, pos: usize) -> Option<Rc<RefCell<Node>>> {
    if pos == 1 {
        let new_node = Node::new(val);
        new_node.borrow_mut().next = head;
        return Some(new_node);
    }

    let mut curr = head.clone();
    let mut count = 1;

    while let Some(node) = curr.clone() {
        if count == pos - 1 {
            let new_node = Node::new(val);
            let next = node.borrow_mut().next.take();
            new_node.borrow_mut().next = next;
            node.borrow_mut().next = Some(new_node);
            break;
        }
        curr = node.borrow().next.clone();
        count += 1;
    }

    head
}

fn print_list(head: Option<Rc<RefCell<Node>>>) {
    let mut curr = head;
    while let Some(node) = curr {
        print!("{} -> ", node.borrow().val);
        curr = node.borrow().next.clone();
    }
    println!("null");
}

fn main() {
    // Create list 1 -> 2 -> 4 -> 5 -> null
    let n1 = Node::new(1);
    let n2 = Node::new(2);
    let n4 = Node::new(4);
    let n5 = Node::new(5);

    n1.borrow_mut().next = Some(n2.clone());
    n2.borrow_mut().next = Some(n4.clone());
    n4.borrow_mut().next = Some(n5.clone());

    let head = Some(n1.clone());

    // Insert 3 at position 3
    let head = insert_at_position(head, 3, 3);

    print_list(head);
}
if pos == 1 { let new_node = Node::new(val); new_node.borrow_mut().next = head; return Some(new_node); }
handle insertion at the start by making new node point to current head
while let Some(node) = curr.clone() { if count == pos - 1 { let new_node = Node::new(val); let next = node.borrow_mut().next.take(); new_node.borrow_mut().next = next; node.borrow_mut().next = Some(new_node); break; } curr = node.borrow().next.clone(); count += 1; }
traverse to node before insertion point, then insert new node by adjusting pointers
OutputSuccess
1 -> 2 -> 3 -> 4 -> 5 -> null
Complexity Analysis
Time: O(n) because we may need to traverse up to n nodes to reach the insertion position
Space: O(1) because insertion uses constant extra space for the new node
vs Alternative: Compared to inserting at the end which may require traversing the whole list, inserting at a known middle position still requires traversal but no shifting of elements like in arrays
Edge Cases
insert at position 1 (start of list)
new node becomes the new head, pointing to old head
DSA Rust
if pos == 1 { ... return Some(new_node); }
insert at position greater than list length + 1
no insertion happens, list remains unchanged
DSA Rust
while let Some(node) = curr.clone() { ... }
empty list and insert at position 1
new node becomes the only node and head
DSA Rust
if pos == 1 { ... return Some(new_node); }
When to Use This Pattern
When a problem asks to add an element exactly at a given position inside a linked list, use the insert at position pattern to adjust pointers carefully.
Common Mistakes
Mistake: Not handling insertion at position 1 separately, causing incorrect head updates
Fix: Add a special case to create new head node when position is 1
Mistake: Losing the rest of the list after insertion by not linking new node's next properly
Fix: Save the next pointer before insertion and link it to the new node's next
Summary
It inserts a new node at a specific position inside a linked list by adjusting pointers.
Use it when you need to add an element exactly in the middle or any position of a linked list.
The key is to stop at the node before the insertion point and link the new node between nodes.

Practice

(1/5)
1. What does inserting a node at a specific middle position in a linked list mean?
easy
A. Removing a node from the middle of the list
B. Adding a new node only at the start of the list
C. Adding a new node only at the end of the list
D. Adding a new node exactly between two existing nodes at a given position

Solution

  1. Step 1: Understand linked list positions

    Positions in a linked list start from 1 at the head. Inserting at a middle position means placing a new node between existing nodes.
  2. Step 2: Define insertion at middle

    Inserting at a specific middle position means the new node will be placed after the node at position (pos-1) and before the node at position pos.
  3. Final Answer:

    Adding a new node exactly between two existing nodes at a given position -> Option D
  4. Quick Check:

    Insert at middle = Add node between nodes [OK]
Hint: Middle insertion means placing node between two nodes [OK]
Common Mistakes:
  • Confusing insertion with deletion
  • Thinking insertion only happens at start or end
  • Ignoring position indexing starting at 1
2. Which Rust code snippet correctly inserts a new node with value 10 at position 3 in a singly linked list?
easy
A. let mut current = &mut head; for _ in 1..2 { current = &mut current.as_mut().unwrap().next; } let new_node = Some(Box::new(Node { val: 10, next: current.take() })); *current = new_node;
B. let mut current = &head; for _ in 1..3 { current = ¤t.unwrap().next; } current = Some(Box::new(Node { val: 10, next: None }));
C. head = Some(Box::new(Node { val: 10, next: head }));
D. let new_node = Node { val: 10, next: None }; head.next = Some(Box::new(new_node));

Solution

  1. Step 1: Traverse to position before insertion

    The loop runs from 1 to 2 (pos-1) to reach node at position 2, using mutable references to modify links.
  2. Step 2: Insert new node at position 3

    Create new node with value 10, set its next to current node's next, then update current's next to new node.
  3. Final Answer:

    Code snippet in option A correctly inserts at position 3 -> Option A
  4. Quick Check:

    Traverse to pos-1, link new node next to current next, update current next [OK]
Hint: Traverse to pos-1, then link new node [OK]
Common Mistakes:
  • Using immutable references when mutable needed
  • Incorrect loop range causing wrong position
  • Not updating links properly causing list break
3. What is the output linked list after inserting value 99 at position 2 in the list 1 -> 2 -> 3 -> null using the following Rust code?
let mut head = Some(Box::new(Node { val: 1, next: Some(Box::new(Node { val: 2, next: Some(Box::new(Node { val: 3, next: None })) })) }));

let mut current = &mut head;
for _ in 1..1 {
    current = &mut current.as_mut().unwrap().next;
}
let new_node = Some(Box::new(Node { val: 99, next: current.as_mut().unwrap().next.take() }));
current.as_mut().unwrap().next = new_node;

// Print list code omitted for brevity
medium
A. 1 -> 99 -> 2 -> 3 -> null
B. 1 -> 2 -> 99 -> 3 -> null
C. 99 -> 1 -> 2 -> 3 -> null
D. 1 -> 2 -> 3 -> 99 -> null

Solution

  1. Step 1: Traverse to node at position 1

    The loop runs from 1 to 1, which is empty, so no iteration; current points to head node with value 1.
  2. Step 2: Insert new node after current

    New node with value 99 is created with next pointing to current's next (node with value 2). Then current's next is updated to new node.
  3. Final Answer:

    1 -> 99 -> 2 -> 3 -> null -> Option A
  4. Quick Check:

    Insert after position 1 adds 99 between 1 and 2 [OK]
Hint: Insert after pos-1 node, new node points to old next [OK]
Common Mistakes:
  • Miscounting loop iterations causing wrong position
  • Not updating next pointers correctly
  • Confusing node values and positions
4. Identify the error in this Rust code snippet that tries to insert a node at position 2 in a singly linked list:
let mut current = &mut head;
for _ in 0..2 {
    current = &mut current.as_mut().unwrap().next;
}
let new_node = Some(Box::new(Node { val: 5, next: current.take() }));
*current = new_node;
medium
A. The code uses immutable references instead of mutable
B. The loop runs too many times, moving current past the insertion point
C. The new node's next pointer is not set correctly
D. The head pointer is not updated after insertion

Solution

  1. Step 1: Analyze loop iteration count

    The loop runs from 0 to 1 (0..2), so two iterations, moving current two nodes ahead, which is past position 2.
  2. Step 2: Understand insertion position

    To insert at position 2, current should point to node at position 1 (pos-1). Loop should run once, not twice.
  3. Final Answer:

    The loop runs too many times, moving current past the insertion point -> Option B
  4. Quick Check:

    Loop count must be pos-1 to insert correctly [OK]
Hint: Loop must run pos-1 times to reach insertion point [OK]
Common Mistakes:
  • Off-by-one error in loop range
  • Not using mutable references for insertion
  • Incorrectly setting new node's next pointer
5. Given a singly linked list and a position that may be beyond the current list length, how should you modify the insertion logic in Rust to insert a node with value 50 at position 5 in the list 10 -> 20 -> 30 -> null?
hard
A. Return an error and do not insert if position is beyond length
B. Insert at the head regardless of position
C. Traverse until the end if position exceeds length, then insert at the end
D. Insert at position 3 instead of 5 automatically

Solution

  1. Step 1: Check position against list length

    Since position 5 is beyond current length 3, traverse until the last node to insert at the end.
  2. Step 2: Insert new node at end

    Once at last node, set its next pointer to new node with value 50 and next as None.
  3. Final Answer:

    Traverse until the end if position exceeds length, then insert at the end -> Option C
  4. Quick Check:

    Insert at end if position too large [OK]
Hint: If position too big, insert at list end [OK]
Common Mistakes:
  • Crashing or panicking when position is too large
  • Ignoring position and inserting at wrong place
  • Not handling None next pointers properly
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