idomatic rust (#1652)

* idomatic rust

* Update linkedlist queue/deque
This commit is contained in:
rongyi
2025-02-10 10:40:29 +08:00
committed by GitHub
parent eec69f45af
commit 00738f5bb4
4 changed files with 29 additions and 26 deletions

View File

@@ -120,7 +120,7 @@ impl<T: Copy> LinkedListDeque<T> {
}
}
self.que_size -= 1; // 更新队列长度
Rc::try_unwrap(old_front).ok().unwrap().into_inner().val
old_front.borrow().val
})
}
// 队尾出队操作
@@ -136,7 +136,7 @@ impl<T: Copy> LinkedListDeque<T> {
}
}
self.que_size -= 1; // 更新队列长度
Rc::try_unwrap(old_rear).ok().unwrap().into_inner().val
old_rear.borrow().val
})
}
}
@@ -163,12 +163,16 @@ impl<T: Copy> LinkedListDeque<T> {
/* 返回数组用于打印 */
pub fn to_array(&self, head: Option<&Rc<RefCell<ListNode<T>>>>) -> Vec<T> {
if let Some(node) = head {
let mut nums = self.to_array(node.borrow().next.as_ref());
nums.insert(0, node.borrow().val);
return nums;
let mut res: Vec<T> = Vec::new();
fn recur<T: Copy>(cur: Option<&Rc<RefCell<ListNode<T>>>>, res: &mut Vec<T>) {
if let Some(cur) = cur {
res.push(cur.borrow().val);
recur(cur.borrow().next.as_ref(), res);
}
}
return Vec::new();
recur(head, &mut res);
res
}
}

View File

@@ -67,7 +67,7 @@ impl<T: Copy> LinkedListQueue<T> {
}
}
self.que_size -= 1;
Rc::try_unwrap(old_front).ok().unwrap().into_inner().val
old_front.borrow().val
})
}
@@ -78,12 +78,18 @@ impl<T: Copy> LinkedListQueue<T> {
/* 将链表转化为 Array 并返回 */
pub fn to_array(&self, head: Option<&Rc<RefCell<ListNode<T>>>>) -> Vec<T> {
if let Some(node) = head {
let mut nums = self.to_array(node.borrow().next.as_ref());
nums.insert(0, node.borrow().val);
return nums;
let mut res: Vec<T> = Vec::new();
fn recur<T: Copy>(cur: Option<&Rc<RefCell<ListNode<T>>>>, res: &mut Vec<T>) {
if let Some(cur) = cur {
res.push(cur.borrow().val);
recur(cur.borrow().next.as_ref(), res);
}
}
return Vec::new();
recur(head, &mut res);
res
}
}

View File

@@ -45,16 +45,10 @@ impl<T: Copy> LinkedListStack<T> {
/* 出栈 */
pub fn pop(&mut self) -> Option<T> {
self.stack_peek.take().map(|old_head| {
match old_head.borrow_mut().next.take() {
Some(new_head) => {
self.stack_peek = Some(new_head);
}
None => {
self.stack_peek = None;
}
}
self.stack_peek = old_head.borrow_mut().next.take();
self.stk_size -= 1;
Rc::try_unwrap(old_head).ok().unwrap().into_inner().val
old_head.borrow().val
})
}