Create and Initialize Doubly Linked List in DSA Rust - Time & Space Complexity
We want to understand how long it takes to create and set up a doubly linked list with several nodes.
How does the time needed grow as we add more nodes?
Analyze the time complexity of the following code snippet.
struct Node {
data: i32,
prev: Option<*mut Node>,
next: Option>,
}
fn create_list(values: &[i32]) -> Option> {
let mut head: Option> = None;
for &val in values.iter().rev() {
let mut new_node = Box::new(Node { data: val, prev: None, next: head });
if let Some(ref mut next_node) = new_node.next {
next_node.prev = Some(&mut *new_node);
}
head = Some(new_node);
}
head
}
This code creates a doubly linked list from an array of values by adding nodes one by one at the front.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the input array once.
- How many times: Exactly once for each element in the input.
Each new node requires a fixed amount of work, done once per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node creations and link updates |
| 100 | About 100 node creations and link updates |
| 1000 | About 1000 node creations and link updates |
Pattern observation: The work grows directly with the number of nodes; doubling nodes doubles work.
Time Complexity: O(n)
This means the time to create the list grows in a straight line with the number of nodes.
[X] Wrong: "Creating a doubly linked list takes more than linear time because of the extra pointers."
[OK] Correct: Each node is created once and pointers are set in constant time, so the extra pointers do not increase the overall time beyond linear.
Knowing how to build linked lists efficiently shows you understand basic data structures and memory links, a key skill in many coding tasks.
"What if we added nodes at the end instead of the front? How would the time complexity change?"
Practice
Solution
Step 1: Understand doubly linked list structure
A doubly linked list has nodes with pointers to both previous and next nodes.Step 2: Identify traversal capability
This structure allows moving forward and backward through the list easily.Final Answer:
To allow traversal in both forward and backward directions -> Option AQuick Check:
Doubly linked list traversal = forward and backward [OK]
- Confusing doubly linked list with arrays
- Thinking it sorts data automatically
- Assuming it prevents duplicates
Solution
Step 1: Understand Rust ownership and pointers
Rust uses Option for next to allow nullable ownership and *mut Node for raw pointer prev.Step 2: Check each option for correctness
struct Node { data: i32, next: Option, prev: Option<*mut Node> } uses Option for next and Option<*mut Node> for prev, which is correct for doubly linked list nodes in Rust.Final Answer:
struct Node { data: i32, next: Option, prev: Option<*mut Node> } -> Option BQuick Check:
Rust doubly linked list node = Option<Box> + raw pointer [OK]
- Using direct Node type causing infinite size error
- Using Box<Node> for prev causing ownership issues
- Not using Option to allow null pointers
struct Node {
data: i32,
next: Option,
prev: Option<*mut Node>,
}
fn main() {
let mut first = Box::new(Node { data: 1, next: None, prev: None });
let mut second = Box::new(Node { data: 2, next: None, prev: None });
first.next = Some(second);
// Set prev pointer
if let Some(ref mut next_node) = first.next {
next_node.prev = Some(&mut *first as *mut Node);
}
println!("{} -> {} -> null", first.data, first.next.as_ref().unwrap().data);
}Solution
Step 1: Analyze node creation and linking
Two nodes created: first with data 1, second with data 2. first.next points to second, second.prev points back to first.Step 2: Understand ownership rules in Rust
Assigning first.next = Some(second) moves ownership of second into first.next. However, second is moved and cannot be used after. Also, setting next_node.prev = Some(&mut *first as *mut Node) involves mutable borrow of first while first is already borrowed mutably, causing ownership conflict.Step 3: Compilation error due to ownership and borrowing rules
The code will not compile due to ownership and borrowing errors.Final Answer:
Compilation error due to ownership -> Option CQuick Check:
Rust ownership rules prevent multiple mutable borrows [OK]
- Confusing order of nodes in print
- Ignoring unsafe pointer usage
- Assuming compilation error without checking code
struct Node {
data: i32,
next: Option,
prev: Option<*mut Node>,
}
fn main() {
let mut node = Node { data: 10, next: None, prev: None };
node.prev = Some(&mut node);
}Solution
Step 1: Understand raw pointer assignment in Rust
Assigning a reference (&mut node) to a raw pointer field (prev) requires an unsafe block because raw pointer dereferencing and assignment are unsafe operations.Step 2: Identify missing unsafe block
The code attempts to assign &mut node to prev without an unsafe block, causing a compilation error.Final Answer:
Cannot assign reference to raw pointer without unsafe block -> Option AQuick Check:
Raw pointer assignments require unsafe block in Rust [OK]
- Ignoring unsafe requirement for raw pointers
- Thinking mutable borrow error occurs here
- Assuming code compiles without error
struct Node {
data: i32,
next: Option,
prev: Option<*mut Node>,
}
fn insert_front(head: &mut Option, value: i32) {
// Fill in the missing code here
}Solution
Step 1: Create new node with next pointing to old head
Use head.take() to move old head out safely and assign to new node's next; prev is None because new node is front.Step 2: Update old head's prev pointer if it exists
If old head exists, set its prev pointer to new node's raw pointer to maintain backward link.Step 3: Update head to point to new node
Assign new node to head to complete insertion at front.Final Answer:
Create new node with next = head.take(), prev = None; if old head exists, set its prev to new node pointer; then set head to new node -> Option DQuick Check:
Insert front updates next, prev, and head correctly [OK]
- Not updating old head's prev pointer
- Setting prev pointer incorrectly
- Overwriting head without moving old head
Ready to prove it?
Pass the test and this pattern moves unknown
