一个 仙人掌堆栈或父指针树是一个堆栈,其中堆栈中的节点具有指向他们的父母,使堆积在多种方式爬升.
我试图在Rust中实现一个可变的Cactus Stack,基于这个不可变的实现,使用Rc<RefCell<T>>模式来传递共享内存:
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Clone, Default)]
pub struct Cactus<T> {
node: Option<Rc<RefCell<Node<T>>>>,
}
#[derive(Clone)]
pub struct Node<T> {
val: Rc<RefCell<T>>,
parent: Option<Rc<RefCell<Node<T>>>>,
len: usize,
}
impl<T> Cactus<T> {
pub fn new() -> Cactus<T> {
Cactus { node: None }
}
pub fn is_empty(&self) -> bool {
self.node.is_none()
}
pub fn len(&self) -> usize {
self.node.as_ref().map_or(0, |x| x.borrow().len)
}
pub fn child(&self, val: T) -> Cactus<T> {
Cactus {
node: Some(Rc::new(RefCell::new(Node { …Run Code Online (Sandbox Code Playgroud)