use std::collections::HashMap;
fn main() {
let mut graph: HashMap<i32, Vec<i32>> = HashMap::new();
graph.entry(1).or_insert(Vec::new()).push(2);
graph.entry(1).or_insert(Vec::new()).push(3);
graph.entry(2).or_insert(Vec::new()).push(4);
graph.entry(3).or_insert(Vec::new()).push(4);
for (node, edges) in &graph {
print!("{} -> ", node);
for e in edges {
print!("{} -> ", e);
}
println!("null");
}
}The code adds edges 2 and 3 to node 1 in that order, then edges 4 to nodes 2 and 3. The adjacency list prints edges in insertion order.
let graph = vec![
(1, vec![2, 3]),
(2, vec![1, 4]),
(3, vec![1]),
(4, vec![2])
];Each edge is counted twice in adjacency lists for undirected graphs. Counting unique edges: (1-2), (1-3), (2-4) gives 3 edges, but since 1-2 and 2-1 are duplicates, total unique edges are 3.
use std::collections::HashMap;
fn main() {
let mut graph: HashMap<i32, Vec<i32>> = HashMap::new();
graph.get_mut(&1).unwrap().push(2);
}The code tries to get a mutable reference to the vector at key 1, but key 1 does not exist yet, so get_mut returns None. Calling unwrap on None causes a panic.
use std::collections::HashMap;
fn main() {
let mut graph: HashMap<i32, Vec<i32>> = HashMap::new();
graph.entry(1).or_insert(Vec::new()).extend(vec![2, 3, 4]);
graph.entry(2).or_insert(Vec::new()).push(1);
if let Some(edges) = graph.get_mut(&1) {
edges.retain(|&x| x != 3);
}
for (node, edges) in &graph {
print!("{} -> ", node);
for e in edges {
print!("{} -> ", e);
}
println!("null");
}
}The code removes edge 3 from node 1's adjacency list, so edges 2 and 4 remain. Node 2 still has edge 1.
An adjacency list stores only existing edges, so memory depends on vertices plus edges (O(V + E)). An adjacency matrix stores all possible edges, so memory depends on square of vertices (O(V^2)).
