Created
June 18, 2021 10:21
-
-
Save zynaxsoft/905eae8ce18dbff0a1c696b637716a6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let mut origin = Node::new(1); | |
let child = Node::new(2); | |
origin.push(&child); | |
let iter = NodeIterator { | |
end: false, | |
head: &origin, | |
}; | |
for i in iter { | |
println!("{}", i); | |
} | |
} | |
struct Node<'a> { | |
value: usize, | |
child: Option<&'a Node<'a>>, | |
} | |
impl<'a> Node<'a> { | |
fn new(v: usize) -> Node<'a> { | |
Node { | |
value: v, | |
child: None, | |
} | |
} | |
fn push(&mut self, n: &'a Node<'a>) { | |
self.child = Some(n); | |
} | |
} | |
struct NodeIterator<'a> { | |
end: bool, | |
head: &'a Node<'a>, | |
} | |
impl<'a> Iterator for NodeIterator<'a> { | |
type Item = usize; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.end { | |
return None; | |
} | |
let result = self.head.value; | |
match self.head.child { | |
Some(child) => self.head = child, | |
None => self.end = true, | |
} | |
Some(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment