A doubly linked list has two pointers per node, allowing traversal forwards and backwards. A singly linked list has only one pointer per node, so it can only be traversed forward.
struct Node {
value: i32,
prev: Option<Box<Node>>,
next: Option<Box<Node>>,
}
fn main() {
// Simplified representation
let list = vec![1, 2, 3];
// Backward traversal output
let output = list.iter().rev().map(|v| v.to_string()).collect::<Vec<_>>().join(" -> ");
println!("{} -> null", output);
}The code reverses the vector representing the list and prints the values from last to first, resulting in "3 -> 2 -> 1 -> null".
struct Node {
value: i32,
prev: Option<Box<Node>>,
next: Option<Box<Node>>,
}
fn main() {
let mut list = vec![1, 2, 3];
list.remove(1); // remove node with value 2
let output = list.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(" -> ");
println!("{} -> null", output);
}After removing node 2, nodes 1 and 3 become neighbors, so the list prints as "1 -> 3 -> null".
struct Node {
value: i32,
prev: Option<Box<Node>>,
next: Option<Box<Node>>,
}
fn insert_front(mut head: Option<Box<Node>>, val: i32) -> Option<Box<Node>> {
let mut new_node = Box::new(Node { value: val, prev: None, next: head });
if let Some(ref mut old_head) = new_node.next {
old_head.prev = Some(new_node);
}
Some(new_node)
}The `head` parameter is moved into `new_node.next`, so attempting to destructure it in the `if let` results in a "use of moved value `head`" error.
Doubly linked list nodes have two pointers (prev and next), so each node uses more memory than singly linked list nodes which have only one pointer.
