guys, I am not an English speaker, so forgive my language first
I have make a list with these code
use std::rc::Rc;
use std::cell::RefCell;
struct ListNode<T> {
value: T,
pub prev: Option<Rc<RefCell<ListNode<T>>>>,
pub next: Option<Rc<RefCell<ListNode<T>>>>
}
pub struct List<T> {
head: Option<Rc<RefCell<ListNode<T>>>>,
tail: Option<Rc<RefCell<ListNode<T>>>>
}
pub struct ListIter<T> {
node: Option<Rc<RefCell<ListNode<T>>>>
}
impl <T> ListNode<T> {
pub fn new(value: T) -> Self {
Self {
value,
prev: None,
next: None
}
}
}
impl <T> List<T> {
pub fn new() -> Self {
Self {
head: None,
tail: None
}
}
pub fn iter(&self) -> ListIter<T> {
ListIter {
node: Option::from(self.head.as_ref().map(|node| {
Rc::clone(node)
}))
}
}
pub fn push(&mut self, value: T) {
let node = Rc::new(RefCell::new(ListNode::new(value)));
if self.head.is_none() {
self.head = Option::from(Rc::clone(&node));
self.tail = Option::from(Rc::clone(&node));
} else {
// node.prev = tail
// tail.next = node
// tail = tail.next
self.tail = self.tail.take().map(|tailnode: Rc<RefCell<ListNode<T>>>| {
// let mut tailnode = tailnode.borrow_mut();
// tailnode.next = Option::from(Rc::clone(&node));
// Rc::clone(&node)
let mut mut_tailnode = tailnode.borrow_mut();
mut_tailnode.next = Option::from(Rc::clone(&node));
let mut mut_node = node.borrow_mut();
mut_node.prev = Option::from(Rc::clone(&tailnode));
Rc::clone(&node)
});
}
}
}
now the most different part is to impl Iterator trait for ListIter
, can you help me out ??
update
the ListIter
is
pub struct ListIter<T> {
node: Option<Rc<RefCell<ListNode<T>>>>
}
and I found a way to impl Iterator trait, but something wrong with my code
impl <T> Iterator for ListIter<T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let result = self.node.map(|node: Rc<RefCell<ListNode<T>>>| {
&node.borrow().value
});
self.node.map(|node: Rc<RefCell<ListNode<T>>>| {
self.node = node.borrow().next
});
return result;
}
}
as you say, I need a lifetime parameters, but that doesn't fit the code, how should I fix it ??