Creating a Singly Linked List from Scratch in DSA Rust - Complexity Walkthrough
We want to understand how the time to build a linked list changes as we add more items.
How does adding nodes one by one affect the total steps needed?
Analyze the time complexity of the following code snippet.
struct Node {
value: i32,
next: Option>,
}
struct LinkedList {
head: Option>,
}
impl LinkedList {
fn new() -> Self {
LinkedList { head: None }
}
fn append(&mut self, val: i32) {
let new_node = Box::new(Node { value: val, next: None });
match self.head.as_mut() {
None => self.head = Some(new_node),
Some(mut current) => {
while let Some(next) = current.next.as_mut() {
current = next;
}
current.next = Some(new_node);
}
}
}
}
This code creates a singly linked list and adds new nodes at the end by walking through the list each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Walking through the list from head to the last node to add a new node.
- How many times: For each append, it may walk through all existing nodes once.
Each new node added requires walking through all nodes already in the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1+2+...+10 = 55 steps |
| 100 | About 5050 steps |
| 1000 | About 500,500 steps |
Pattern observation: The total steps grow roughly like the square of the number of nodes.
Time Complexity: O(n²)
This means adding n nodes one by one by walking to the end each time takes time proportional to n squared.
[X] Wrong: "Appending a node always takes the same time no matter how big the list is."
[OK] Correct: Because this code walks through all existing nodes each time, so adding nodes gets slower as the list grows.
Understanding how linked list operations scale helps you explain trade-offs and choose better designs in real coding tasks.
"What if we kept a pointer to the last node to avoid walking the list each time? How would the time complexity change?"
Practice
Singly Linked List in data structures?Solution
Step 1: Understand the structure of a singly linked list
A singly linked list stores elements in nodes where each node points to the next node, forming a chain.Step 2: Compare with other data structures
Unlike arrays, singly linked lists do not provide direct index access and unlike trees, they have a single linear chain of nodes.Final Answer:
To store elements in a linear order where each element points to the next -> Option DQuick Check:
Singly Linked List = Linear chain with next pointers [OK]
- Confusing linked lists with arrays having direct index access
- Thinking linked lists are hierarchical like trees
- Assuming nodes can point backward in singly linked lists
Solution
Step 1: Understand Rust ownership and pointers
Rust requires heap allocation for recursive types like linked lists, soBoxis used to own the next node.Step 2: Analyze each option
struct Node { value: i32, next: Option } usesOptionallowing for a nullable next pointer, which is correct. struct Node { value: i32, next: Node } is invalid because it causes infinite size. struct Node { value: i32, next: &Node } uses a reference without lifetime, which is invalid. struct Node { value: i32, next: Vec<Node> } uses a vector which is not suitable for singly linked list next pointer.Final Answer:
struct Node { value: i32, next: Option } -> Option CQuick Check:
Use Option for next pointer in Rust [OK]
- Using direct Node type causes infinite size error
- Using references without lifetimes for next pointer
- Using Vec<Node> instead of a single next node pointer
struct Node {
value: i32,
next: Option,
}
fn main() {
let third = Node { value: 3, next: None };
let second = Node { value: 2, next: Some(Box::new(third)) };
let first = Node { value: 1, next: Some(Box::new(second)) };
let mut current = &first;
while let Some(ref next_node) = current.next {
println!("{} ->", current.value);
current = next_node;
}
println!("{} -> null", current.value);
}Solution
Step 1: Trace the linked list creation
Nodes are created in reverse order: third (3, None), second (2, Some(third)), first (1, Some(second)). So the list is 1 -> 2 -> 3 -> null.Step 2: Follow the print loop
The loop prints current.value followed by '->' while current.next is Some. It prints 1 ->, then 2 ->, then exits loop at 3 (next is None) and prints 3 -> null.Final Answer:
1 -> 2 -> 3 -> null -> Option BQuick Check:
Prints nodes in order from first to last [OK]
- Printing nodes in reverse order by mistake
- Missing the last node print with 'null'
- Confusing Option with direct node causing errors
struct Node {
value: i32,
next: Option,
}
fn main() {
let node1 = Node { value: 1, next: None };
let node2 = Node { value: 2, next: node1 };
}Solution
Step 1: Check the type of next field
The next field expects an Option, but node1 is a Node, not wrapped in Box or Option.Step 2: Understand Rust type requirements
Rust requires the next pointer to be boxed and wrapped in Option to handle ownership and nullability. Directly assigning node1 causes a type mismatch.Final Answer:
next field must be Option, but node1 is Node type -> Option AQuick Check:
next must be Option not Node [OK]
- Assigning Node directly instead of Option
- Ignoring Rust ownership rules for recursive types
- Assuming semicolon missing causes error here
append to add a new node at the end of a singly linked list in Rust. Which approach correctly handles ownership and mutability to traverse and append the node?Solution
Step 1: Understand Rust ownership and mutability for linked lists
To modify the list, you need a mutable reference to the next pointer (Option) to traverse and update it safely.Step 2: Analyze each option
Use a mutable reference to Option and loop until next is None, then set next to Some(new_node) correctly uses mutable references to traverse until the end and then sets next to Some(new_node). Use an immutable reference to Node and assign next directly without mutability uses immutable reference which cannot modify. Clone the entire list and add the new node at the front clones the list which is inefficient and not appending at end. Use unsafe pointers to bypass Rust ownership rules uses unsafe code which is discouraged.Final Answer:
Use a mutable reference to Option and loop until next is None, then set next to Some(new_node) -> Option AQuick Check:
Mutable reference to next pointer needed for append [OK]
- Using immutable references preventing modification
- Trying to assign next without Option or Box
- Using unsafe code unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
