介绍
视频地址:https://www.bilibili.com/video/av78062009/
相关源码:https://github.com/anonymousGiga/Rust-link-list
详细内容
pop front
上一节,我们给双链表实现了new和push front方法,本节我们实现pop front,代码如下:
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|node| {
match node.borrow_mut().next.take() {
Some(next) => {
next.borrow_mut().prev.take();
self.head = Some(next);
}
None => {
self.tail.take();
}
}
//取值使用into_inner
Rc::try_unwrap(node).ok().unwrap().into_inner().elem
})
}
在上述代码中,需要注意的是,我们在取出节点中的值的时候要使用into_inner。
测试
下面我们添加测试代码:
#[cfg(test)]
mod tests {
use super::List;
#[test]
fn basics() {
let mut list = List::new();
assert_eq!(list.pop_front(), None);
list.push_front(1);
list.push_front(2);
list.push_front(3);
assert_eq!(list.pop_front(), Some(3));
assert_eq!(list.pop_front(), Some(2));
list.push_front(4);
list.push_front(5);
assert_eq!(list.pop_front(), Some(5));
assert_eq!(list.pop_front(), Some(4));
assert_eq!(list.pop_front(), Some(1));
assert_eq!(list.pop_front(), None);
}
}
完整代码
完整代码如下:
use std::rc::Rc;
use std::cell::RefCell;
pub struct List<T> {
head: Link<T>,
tail: Link<T>,
}
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
elem: T,
next: Link<T>,
prev: Link<T>,
}
impl<T> Node<T> {
fn new(elem: T) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Node {
elem: elem,
prev: None,
next: None,
}))
}
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, tail: None }
}
pub fn push_front(&mut self, elem: T) {
let node = Node::new(elem);
match self.head.take() {
Some(head) => {
//取可变引用使用borrow_mut
head.borrow_mut().prev = Some(node.clone());
node.borrow_mut().next = Some(head);
self.head = Some(node);
}
None => {
self.tail = Some(node.clone());
self.head = Some(node);
}
}
}
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|node| {
match node.borrow_mut().next.take() {
Some(next) => {
next.borrow_mut().prev.take();
self.head = Some(next);
}
None => {
self.tail.take();
}
}
//取值使用into_inner
Rc::try_unwrap(node).ok().unwrap().into_inner().elem
})
}
}
#[cfg(test)]
mod tests {
use super::List;
#[test]
fn basics() {
let mut list = List::new();
assert_eq!(list.pop_front(), None);
list.push_front(1);
list.push_front(2);
list.push_front(3);
assert_eq!(list.pop_front(), Some(3));
assert_eq!(list.pop_front(), Some(2));
list.push_front(4);
list.push_front(5);
assert_eq!(list.pop_front(), Some(5));
assert_eq!(list.pop_front(), Some(4));
assert_eq!(list.pop_front(), Some(1));
assert_eq!(list.pop_front(), None);
}
}