Bird
Raised Fist0
DSA Rustprogramming

Doubly Linked List Structure and Node Design in DSA Rust

Choose your learning style10 modes available
Mental Model
A doubly linked list is a chain of nodes where each node knows both its neighbor before and after it.
Analogy: Imagine a train where each car is connected to the one in front and the one behind, so you can move forward or backward easily.
null ← 1 ↔ 2 ↔ 3 -> null
Dry Run Walkthrough
Input: list: 1 ↔ 2 ↔ 3 (three nodes connected both ways)
Goal: Understand how each node links to the previous and next nodes
Step 1: Create node 1 with no previous and next pointing to node 2
null ← [1] -> 2 -> 3 -> null
Why: First node has no previous, next points to second node
Step 2: Create node 2 with previous pointing to node 1 and next pointing to node 3
null ← 1 ↔ [2] -> 3 -> null
Why: Middle node links back to node 1 and forward to node 3
Step 3: Create node 3 with previous pointing to node 2 and no next node
null ← 1 ↔ 2 ↔ [3] -> null
Why: Last node has no next, previous points to node 2
Result:
null ← 1 ↔ 2 ↔ 3 -> null
Annotated Code
DSA Rust
use std::rc::{Rc, Weak};
use std::cell::RefCell;

// Node struct for doubly linked list
struct Node {
    value: i32,
    prev: Option<Weak<RefCell<Node>>>,
    next: Option<Rc<RefCell<Node>>>,
}

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

// Function to create a doubly linked list with 3 nodes: 1 <-> 2 <-> 3
fn create_list() -> Rc<RefCell<Node>> {
    let node1 = Node::new(1);
    let node2 = Node::new(2);
    let node3 = Node::new(3);

    // Link node1 to node2
    node1.borrow_mut().next = Some(Rc::clone(&node2));
    node2.borrow_mut().prev = Some(Rc::downgrade(&node1));

    // Link node2 to node3
    node2.borrow_mut().next = Some(Rc::clone(&node3));
    node3.borrow_mut().prev = Some(Rc::downgrade(&node2));

    node1
}

// Function to print the list forward
fn print_forward(head: Rc<RefCell<Node>>) {
    let mut current = Some(head);
    while let Some(node_rc) = current {
        let node = node_rc.borrow();
        print!("{}", node.value);
        if node.next.is_some() {
            print!(" ↔ ");
        }
        current = node.next.as_ref().map(Rc::clone);
    }
    println!();
}

fn main() {
    let head = create_list();
    print_forward(head);
}
node1.borrow_mut().next = Some(Rc::clone(&node2));
Link node1's next pointer to node2
node2.borrow_mut().prev = Some(Rc::downgrade(&node1));
Link node2's previous pointer back to node1
node2.borrow_mut().next = Some(Rc::clone(&node3));
Link node2's next pointer to node3
node3.borrow_mut().prev = Some(Rc::downgrade(&node2));
Link node3's previous pointer back to node2
while let Some(node_rc) = current {
Traverse nodes forward until no next node
current = node.next.as_ref().map(Rc::clone);
Advance current to next node
OutputSuccess
1 ↔ 2 ↔ 3
Complexity Analysis
Time: O(n) because creating and linking n nodes requires visiting each node once
Space: O(n) because each node stores pointers and data separately
vs Alternative: Compared to singly linked list, doubly linked list uses extra space for previous pointers but allows backward traversal
Edge Cases
Empty list (no nodes)
No nodes to link, head is None or null
DSA Rust
N/A - create_list always returns at least one node in this example
Single node list
Node's prev and next pointers are None
DSA Rust
Node::new sets prev and next to None by default
When to Use This Pattern
When you need to move forward and backward through a list easily, look for doubly linked list structure to store previous and next links.
Common Mistakes
Mistake: Forgetting to set the previous pointer when linking nodes
Fix: Always set both next and prev pointers when connecting nodes
Mistake: Using strong references for both prev and next causing memory leaks
Fix: Use weak references for prev pointers to avoid reference cycles
Summary
A doubly linked list node stores links to both previous and next nodes.
Use it when you want to traverse a list in both directions easily.
The key is that each node knows its neighbors on both sides, like train cars connected front and back.

Practice

(1/5)
1. What is the main advantage of a doubly linked list over a singly linked list?
easy
A. It allows traversal in both forward and backward directions
B. It uses less memory per node
C. It requires fewer pointers per node
D. It can only be traversed forward

Solution

  1. Step 1: Understand node pointers in doubly linked list

    A doubly linked list node has two pointers: one to the next node and one to the previous node.
  2. Step 2: Compare traversal capabilities

    This allows moving forward and backward through the list, unlike singly linked lists which only allow forward traversal.
  3. Final Answer:

    It allows traversal in both forward and backward directions -> Option A
  4. Quick Check:

    Doubly linked list = two-way traversal [OK]
Hint: Remember: two pointers mean two directions [OK]
Common Mistakes:
  • Thinking it uses less memory than singly linked list
  • Assuming it only allows forward traversal
  • Confusing pointer count with memory usage
2. Which of the following is the correct Rust struct definition for a doubly linked list node holding an integer value?
easy
A. struct Node { value: i32, next: Option, prev: Option<*mut Node> }
B. struct Node { value: i32, next: Option, prev: Option }
C. struct Node { value: i32, next: Option, prev: Option }
D. struct Node { value: i32, next: Option<Node>, prev: Option<Node> }

Solution

  1. Step 1: Understand ownership and pointers in Rust doubly linked list

    Rust's ownership rules prevent two owning pointers to the same data. The next pointer can own the next node using Box, but the prev pointer must be a raw pointer or weak reference to avoid ownership conflicts.
  2. Step 2: Analyze options for prev pointer

    struct Node { value: i32, next: Option, prev: Option<*mut Node> } uses Option<*mut Node> (a raw mutable pointer) for prev, which is common in unsafe doubly linked list implementations. struct Node { value: i32, next: Option, prev: Option } incorrectly uses Box for prev, causing double ownership. struct Node { value: i32, next: Option, prev: Option } uses Rc which is for shared ownership but not mutable by default. struct Node { value: i32, next: Option<Node>, prev: Option<Node> } uses Option<Node> which is invalid because Node is not sized.
  3. Final Answer:

    struct Node { value: i32, next: Option, prev: Option<*mut Node> } -> Option A
  4. Quick Check:

    Prev pointer = raw pointer to avoid ownership [OK]
Hint: Prev pointer often uses raw pointer in Rust doubly linked lists [OK]
Common Mistakes:
  • Using Box for both next and prev causing ownership errors
  • Using Rc without mutability for prev
  • Trying to store Node directly without Box or pointer
3. Given the following Rust code snippet for a doubly linked list node insertion, what will be the printed output?
struct Node {
    value: i32,
    next: Option,
    prev: Option<*mut Node>,
}

fn main() {
    let mut first = Box::new(Node { value: 1, next: None, prev: None });
    let mut second = Box::new(Node { value: 2, next: None, prev: None });

    second.prev = Some(&mut *first as *mut _);
    first.next = Some(second);

    println!("{} -> {}", first.value, first.next.as_ref().unwrap().value);
}
medium
A. Runtime panic due to null pointer
B. 2 -> 1
C. Compilation error due to borrowing
D. 1 -> 2

Solution

  1. Step 1: Understand node creation and linking

    Two nodes are created: first with value 1, second with value 2. The second node's prev pointer is set to point to first. The first node's next pointer is set to own second.
  2. Step 2: Analyze the print statement

    The print accesses first.value (1) and first.next's value (2). Since first.next is Some(second), unwrap() succeeds and prints "1 -> 2".
  3. Final Answer:

    1 -> 2 -> Option D
  4. Quick Check:

    First node value then next node value = 1 -> 2 [OK]
Hint: Print first node then unwrap next for correct order [OK]
Common Mistakes:
  • Confusing prev pointer direction
  • Expecting compilation error due to unsafe pointer
  • Assuming runtime panic without dereferencing prev
4. Identify the error in this Rust doubly linked list node struct and fix it:
struct Node {
    value: i32,
    next: Option,
    prev: Option,
}
medium
A. Change next to Option for shared ownership
B. Remove prev pointer completely
C. Change prev to Option<*mut Node> to avoid double ownership
D. Use Option<Node> for both next and prev

Solution

  1. Step 1: Identify ownership problem with prev pointer

    Using Box for both next and prev means both own the node, causing double ownership which Rust disallows.
  2. Step 2: Fix by changing prev pointer type

    Changing prev to Option<*mut Node> uses a raw pointer, which does not own the node and avoids ownership conflicts.
  3. Final Answer:

    Change prev to Option<*mut Node> to avoid double ownership -> Option C
  4. Quick Check:

    Prev pointer must not own node to prevent ownership error [OK]
Hint: Prev pointer uses raw pointer to avoid ownership conflicts [OK]
Common Mistakes:
  • Using Box for prev causing compile errors
  • Trying to remove prev pointer losing backward traversal
  • Using Option<Node> which is invalid due to size
5. You want to implement a safe doubly linked list in Rust that allows multiple owners of nodes and mutable access. Which combination of pointer types is the best design choice?
hard
A. Use raw pointers (*mut Node) for both next and prev
B. Use Rc for next and Weak for prev
C. Use Option<Node> for next and Option<Node> for prev
D. Use Box<Node> for next and Box<Node> for prev

Solution

  1. Step 1: Understand ownership and mutability requirements

    Multiple owners require reference counting (Rc). Mutable access requires interior mutability (RefCell).
  2. Step 2: Choose pointer types for next and prev

    Next pointer uses Rc to own and allow mutation. Prev pointer uses Weak to avoid strong reference cycles and memory leaks.
  3. Final Answer:

    Use Rc for next and Weak for prev -> Option B
  4. Quick Check:

    Rc + RefCell + Weak = safe mutable doubly linked list [OK]
Hint: Use Rc + RefCell for ownership and Weak for back links [OK]
Common Mistakes:
  • Using Box for both pointers causing ownership errors
  • Using raw pointers risking unsafe code
  • Ignoring Weak to prevent reference cycles
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