too-many-lists/deque/layout #980
Replies: 2 comments 1 reply
-
pop的代码有些难懂,我这写了注释,大家看一下吧
|
Beta Was this translation helpful? Give feedback.
1 reply
-
impl<T> List<T> {
pub fn new() -> Self{
List { head: None, tail: None }
}
pub fn push_front(&mut self,elem: T){
let new_head = Node::new(elem);
// 头部插入
if let Some(old_head) = self.head.take() {
// 非空链表
// old_head.prev = new_head
// refCell.borrow_mut() : 解refcell
old_head.borrow_mut().prev = Some(new_head.clone());
// new_head.next -> old_head
new_head.borrow_mut().next = Some(old_head/* 后边不会用到old_head这个变量, 直接将所有权转移就行*/);
// head -> new_head
self.head = Some(new_head);
} else {
// 空链表
// tail -> new_head
self.tail = Some(new_head.clone());
// head -> new_head
self.head = Some(new_head);
}
}
pub fn pop_front(&mut self) -> Option<T>{
let old_head = self.head.take()?;
if let Some(new_head) = old_head.borrow_mut().next.take() {
// 非空链表
// new_head.prev = null
new_head.borrow_mut().prev.take();
// list.head = new_head
self.head = Some(new_head);
} else {
// 空链表
// tail -> null
self.tail.take();
}
// ?
Some(Rc::try_unwrap(old_head).ok().unwrap().into_inner().elem)
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
too-many-lists/deque/layout
https://course.rs/too-many-lists/deque/layout.html
Beta Was this translation helpful? Give feedback.
All reactions