Решение на упр.08 задача 1 от Емилиан Янев
Резултати
- 4 точки от тестове
- 0 бонус точки
- 4 точки общо
- 2 успешни тест(а)
- 0 неуспешни тест(а)
Код
type Link<T> = Option<std::rc::Rc<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
pub struct List<T> {
head: Link<T>,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|rc| &rc.elem)
}
pub fn tail(&self) -> List<T> {
List {
head: self.head.as_ref().and_then(|rc| rc.next.clone()),
}
}
pub fn prepend(&self, value: T) -> List<T> {
List {
head: Some(std::rc::Rc::new(Node {
elem: value,
next: self.head.clone(),
}))
}
}
pub fn iter(&self) -> Iter<'_, T> {
Iter {
next: self.head.as_deref(),
}
}
}
impl<T> Drop for List<T> {
fn drop(&mut self) {
let mut current = self.head.take();
while let Some(node) = current {
if std::rc::Rc::strong_count(&node) == 1 {
current = node.next.clone();
} else {
break;
}
}
}
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
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_deref();
&node.elem
})
}
}
fn main() {
let mut list = List::new();
for i in 0..1_000_000 {
list = list.prepend(i);
}
std::mem::drop(list);
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling unicode-ident v1.0.22
Compiling quote v1.0.42
Compiling futures-core v0.3.31
Compiling futures-sink v0.3.31
Compiling futures-channel v0.3.31
Compiling memchr v2.7.6
Compiling syn v2.0.111
Compiling slab v0.4.11
Compiling futures-task v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling solution v0.1.0 (/tmp/d20251211-1757769-1awqm74/solution)
warning: function `main` is never used
--> src/lib.rs:74:4
|
74 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (lib) generated 1 warning
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
warning: function `main` is never used
--> tests/../src/lib.rs:74:4
|
74 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (test "solution_test") generated 1 warning
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.50s
Running tests/solution_test.rs (target/debug/deps/solution_test-ee0783488e12dce9)
running 2 tests
test solution_test::test_iterator ... ok
test solution_test::test_list ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
