Rust Graph

 avatar
unknown
rust
10 hours ago
895 B
285
Indexable
#[derive(Clone)]
struct Node<T> {
    index: usize,
    data : Rc<T>
}

struct Graph {
    list_repr: Vec<Vec<usize>>,
    // matrix_repr: Vec<Vec<bool>>,
}

impl Graph {
    fn new() -> Self {
        Graph {
            list_repr: vec![vec![]; 0],
            // matrix_repr: vec![vec![false; 5]; 5],
        }
    }

    fn connect<T, C>(&mut self, a: &Node<T>, b: &Node<C>) {
        self.list_repr[a.index].push(b.index);
    }

    fn add_node<T>(&mut self, data : T) -> Node<T> {
        let new_node = Node {
            index: self.list_repr.len(),
            data: Rc::new(data)
        };
        self.list_repr.push(vec![]);
        new_node
    }
}

#[test]
fn graph_test() {
    let mut graph = Graph::new();

    let node_a : Node = graph.add_node(123);
    let node_b : Node = graph.add_node("work".to_owned());

    graph.connect(&node_a, &node_b);

    print!("{}", graph);
}
Editor is loading...
Leave a Comment