mut self) -> Option {
self.tail.take().map(|old_tail| {
if let Some(new_tail) = old_tail.borrow_mut().prev.take() {
new_tail.borrow_mut().next = None;
self.tail = Some(new_tail);
} else {
self.head = None;
}
Rc::try_unwrap(old_tail).ok().unwrap().into_inner().value
})
}
fn print_forward(&self) {
let mut current = self.head.clone();
while let Some(node) = current {
println!("{:?}", node.borrow().value);
current = node.borrow().next.clone();
}
}
fn print_backward(&self) {
let mut current = self.tail.clone();
while let Some(node) = current {
println!("{:?}", node.borrow().value);
current = node.borrow().prev.clone();
}
}
}
fn main() {
let mut list: DoublyLinkedList = DoublyLinkedList::new();
list.push_front(3);
list.push_front(2);
list.push_front(1);
list.push_back(4);
list.push_back(5);
list.print_forward();
println!("---");
list.print_backward();
}
This implementation uses Rust's `Rc` (reference-counted) and `RefCell` types to allow for multiple ownership and interior mutability, respectively. The `Node` struct represents each node in the doubly linked list, with `prev` and `next` pointers to the previous and next nodes. The `DoublyLinkedList` struct manages the head and tail nodes of the list and provides methods to push elements to the front and back, pop elements from the front and back, and print the list in forward and backward order.
In the `main` function, a `DoublyLinkedList` of `i32` values is created and elements are pushed to the front and back of the list. Finally, the list is printed in forward and backward order using the `print_forward` and `print_backward` methods.