struct Node {
data: i32,
prev: Option<Box<Node>>,
next: Option<Box<Node>>,
}
// Simplified representation for this example
// Original list: 1 <-> 2 <-> 3 <-> null
// After reverse, what is the list?
fn main() {
let mut list = vec![1, 2, 3];
list.reverse();
for val in list {
print!("{} <-> ", val);
}
print!("null");
}Reversing the list changes the order from 1, 2, 3 to 3, 2, 1. The doubly linked list uses <-> to show links in both directions, so the output shows the reversed order with arrows pointing both ways.
In a doubly linked list, each node has two pointers: prev and next. To reverse the list, you must swap these pointers for every node so that the direction of traversal is reversed.
fn reverse(mut head: Option<Box<Node>>) -> Option<Box<Node>> {
let mut current = head;
while let Some(mut node) = current {
let temp = node.next;
node.next = node.prev;
node.prev = temp;
current = node.prev;
}
head
}The code tries to move out of node.next and node.prev while node is borrowed, which Rust does not allow. This causes a compilation error about moving out of borrowed content.
let mut list = vec![10, 20, 30, 40]; list.reverse(); for val in list { print!("{} <-> ", val); } print!("null");
The list is reversed, so the order becomes 40, 30, 20, 10. The doubly linked list notation uses <-> to show links in both directions.
struct Node {
data: i32,
prev: Option<Box<Node>>,
next: Option<Box<Node>>,
}
fn main() {
let mut list = vec![42];
list.reverse();
for val in list {
print!("{} <-> ", val);
}
print!("null");
}A list with one node reversed remains the same. The output shows the node value followed by <-> null indicating the end of the list.
