linked_list/
linked_list.rs

1use generic_cursors::simple::MutRefStack;
2
3#[derive(Debug, Clone)]
4/// A simple recursive data structure
5pub struct SimpleLinkedList<T> {
6    data: T,
7    child: Option<Box<SimpleLinkedList<T>>>,
8}
9
10impl<T> SimpleLinkedList<T> {
11    fn child_mut(&mut self) -> Option<&mut Self> {
12        self.child.as_deref_mut()
13    }
14    fn insert_child(&mut self, new_child: Box<Self>) -> Option<Box<Self>> {
15        std::mem::replace(&mut self.child, Some(new_child))
16    }
17}
18
19fn main() {
20    let mut the_t = SimpleLinkedList {
21        data: 0_u32,
22        child: None,
23    };
24
25    // Using a MutRefStack to descend the data structure.
26    // This could be done with regular mutable references.
27    let mut stack = MutRefStack::new(&mut the_t);
28    for i in 1..10 {
29        stack.top_mut().insert_child(Box::new(SimpleLinkedList {
30            data: i,
31            child: None,
32        }));
33        stack.descend_with(SimpleLinkedList::child_mut).unwrap();
34    }
35    println!("{:?}", the_t);
36
37    // Using regular mutable references to descend the data structure.
38    let mut top = &mut the_t;
39    for i in 1..10 {
40        top.insert_child(Box::new(SimpleLinkedList {
41            data: i,
42            child: None,
43        }));
44        top = top.child_mut().unwrap();
45    }
46    println!("{:?}", the_t);
47
48    // Using a MutRefStack to descend *and then ascend* the data structure.
49    // This cannot be done with regular mutable references.
50    let mut stack = MutRefStack::new(&mut the_t);
51    println!("Stack currently at item with value: {}", stack.top().data);
52    loop {
53        if let None = stack.descend_with(SimpleLinkedList::child_mut) {
54            println!("Reached the end of the linked list!");
55            break;
56        }
57        println!("Descended successfully!");
58        println!("Stack currently at item with value: {}", stack.top().data);
59    }
60    println!("Stack currently at item with value: {}", stack.top().data);
61    loop {
62        if let None = stack.ascend() {
63            println!("Reached the head of the linked list!");
64            break;
65        }
66        println!("Ascended successfully!");
67        println!("Stack currently at item with value: {}", stack.top().data);
68    }
69}