Решение на упр.08 задача 1 от Стилиян Иванов
Код
use std::rc::Rc;
use std::mem;
type Link<T> = Option<Rc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct List<T> {
head: Link<T>,
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
pub fn tail(&self) -> List<T> {
self.head.as_ref().map_or(
List::new(),
|node| List {
head: node.next.clone(),
},
)
}
pub fn prepend(&self, value: T) -> List<T> {
List {
head: Some(Rc::new(Node {
elem: value,
next: self.head.clone(),
})),
}
}
pub fn iter(&self) -> Iter<'_, T> {
Iter {
next: self.head.as_ref().map(|node| &**node)
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|rc| &**rc);
&node.elem
})
}
}
impl<T> Drop for List<T> {
fn drop(&mut self) {
let mut current_link = mem::take(&mut self.head);
while let Some(rc_node) = current_link {
if Rc::strong_count(&rc_node) > 1 {
break;
}
let node = match Rc::try_unwrap(rc_node) {
Ok(node) => node,
Err(_) => unreachable!(),
};
current_link = node.next;
}
}
}
fn main() {
let mut list = List::new();
for i in 0..1_000_000 {
list = list.prepend(i);
}
std::mem::drop(list);
println!("Програмата завърши успешно.");
}
