我正在编程一个LinkedList。这是我的结构,我需要一些关于执行按索引获取(usinze(方法的帮助。
这是我的结构代码:
struct Node<T>
where
T: Clone,
{
value: T,
prev: Option<Rc<RefCell<Node<T>>>>,
next: Option<Rc<RefCell<Node<T>>>>,
}
impl<T> Node<T>
where
T: Clone,
{
pub fn new(val: T) -> Self {
Node {
value: val,
prev: None,
next: None,
}
}
}
struct ListNode<T: Clone> {
length: usize,
header: Option<Rc<RefCell<Node<T>>>>,
tail: Option<Rc<RefCell<Node<T>>>>,
}
现在我想执行一个get方法,通过索引获取T:usize,有问题
impl<T> ListNode<T>
where
T: Clone,
{
pub fn get(&self, idx: usize) -> Option<T> {
let mut p = &self.header;
for _ in 0..=idx {
if let Some(x) = p {
let clone_p = Rc::clone(x);
// Problem 1 is here, I want p point to the next
p = &((*clone_p).borrow().next);
} else {
return None;
}
}
if let Some(x) = p {
let clone_p = Rc::clone(x);
return Some((*clone_p).borrow().value.clone());
}
None
}
}
如何解决此问题?
我想我必须克隆ReCell,这是代码,有优化吗?
pub fn get(&self, idx: usize) -> Option<T> {
if let Some(p) = &self.header {
let mut ptr: Option<Rc<RefCell<Node<T>>>> = None;
for _ in 0..=idx {
let v = Rc::clone(p);
let next = &(*v).borrow().next;
if let Some(x) = next {
ptr = Some(Rc::clone(x));
} else {
return None;
}
}
if let Some(x) = ptr {
return Some((*x).borrow().value.clone());
}
}
None
}