Improve list by adding iterator trait

This commit is contained in:
Quentin Legot 2023-02-17 09:45:47 +01:00 committed by François Autin
parent 407480bcd4
commit 958407ab77
No known key found for this signature in database
GPG Key ID: 343F5D382E1DD77C

View File

@ -77,7 +77,7 @@ impl<T> DoublyLinkedList<T> {
}
}
/// Remove the item at the end of the list
/// Retrieve and remove the item at the end of the list
pub fn pop_back(&mut self) -> Option<T> {
self.tail.take().map(|prev_tail| {
self.size -= 1;
@ -94,7 +94,7 @@ impl<T> DoublyLinkedList<T> {
})
}
/// Remove the item at the start of the list
/// Retrieve and remove the item at the start of the list
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|prev_head| {
self.size -= 1;
@ -124,6 +124,43 @@ impl<T> Drop for DoublyLinkedList<T> {
}
}
impl<T> IntoIterator for DoublyLinkedList<T> {
type Item = <ListIterator<T> as Iterator>::Item;
type IntoIter = ListIterator<T>;
fn into_iter(self) -> Self::IntoIter {
Self::IntoIter::new(self)
}
}
pub struct ListIterator<T> {
list: DoublyLinkedList<T>,
}
impl<T> ListIterator<T> {
fn new(list: DoublyLinkedList<T>) -> Self {
Self { list }
}
}
impl<T> Iterator for ListIterator<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.list.pop_front()
}
}
impl<T> DoubleEndedIterator for ListIterator<T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.list.pop_back()
}
}
pub type List<T> = DoublyLinkedList<T>;
pub type ListInt = List<i32>;
#[cfg(test)]
mod test {
@ -138,5 +175,4 @@ mod test {
assert_eq!(list.pop_front().unwrap(), 5);
}
}