I'm trying to implement building a singly-linked list from an Iterator
, keeping the order of elements.
The structure is defined as:
#[derive(Debug)]
struct List<T> {
list: Node<T>,
}
type Node<T> = Option<Box<Link<T>>>;
#[derive(Debug)]
struct Link<T> {
head: T,
tail: Node<T>,
}
I was thinking of keeping a mutable reference to the end of the list and expanding it while iterating. However, I couldn't figure out how this could be done. The (non-working) idea was:
impl<T> List<T> {
pub fn from_iterator(i: &mut Iterator<Item = T>) -> Self {
let mut list = List { list: None };
{
let mut last: &mut Node<T> = &mut list.list;
for x in i {
let singleton = Box::new(Link {
head: x,
tail: None,
});
*last = Some(singleton);
// --> I aim for something like the line below. Of course
// 'singleton' can't be accessed at this point, but even if I
// match on *last to retrieve it, still I couldn't figure out how
// to properly reference the new tail.
// last = &mut singleton.tail;
}
}
list
}
}
It'd be possible to just build the list in reverse and then reverse it afterwards with the same time complexity, but I was curious if the above approach is ever possible in Rust.