Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main()
- {
- let mut l: LinkedList<int> = LinkedList::new();
- l = l.prepend(5);
- l = l.prepend(2);
- l = l.prepend(8);
- l = l.prepend(100);
- for n in l.iter() {
- println!("{}", n);
- }
- }
- enum LinkedList<T>
- {
- Node(T, Box<LinkedList<T>>),
- Nil
- }
- struct LinkedListIterator<T>
- {
- current_node: Box<LinkedList<T>>
- }
- impl<T> LinkedList<T>
- {
- fn new() -> LinkedList<T> {
- Nil
- }
- fn prepend(self, item: T) -> LinkedList<T> {
- Node(item, box self)
- }
- fn get(self, index: u32) -> Option<T> {
- if index == 0 {
- match self {
- Nil => None,
- Node(val, _) => Some(val)
- }
- } else {
- match self {
- Nil => None,
- Node(_, next) => next.get(index - 1)
- }
- }
- }
- fn iter(self) -> LinkedListIterator<T> {
- LinkedListIterator<T> { current_node: self }
- }
- }
- impl<T> Iterator<T> for LinkedListIterator<T>
- {
- fn next(&mut self) -> Option<T> {
- match self.current_node {
- Node(val, next_node) => {
- self = next_node;
- Some(val)
- }
- Nil => None
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement