Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. use std::cell::Cell;
  2. use std::collections::HashMap;
  3.  
  4. pub type Id = i64;
  5.  
  6. struct Node<'a> {
  7. pub id: Id,
  8. pub next: Cell<Option<&'a Node<'a>>>
  9. }
  10.  
  11. struct RawNode {
  12. pub id: Id,
  13. pub next: Id
  14. }
  15.  
  16. fn main() {
  17. let raw_nodes = vec![
  18. RawNode { id: 1, next: 2},
  19. RawNode { id: 2, next: 1}
  20. ];
  21.  
  22. let nodes = build_nodes(&raw_nodes);
  23.  
  24. for (id, node) in nodes {
  25. println!("{} -> {}", id, node.next.get().and_then(|n| Some(n.id)).unwrap_or(-1));
  26. }
  27. }
  28.  
  29. fn build_nodes<'a>(raw_nodes: &Vec<RawNode>) -> HashMap<Id, Node<'a>> {
  30. let mut nodes = HashMap::new();
  31.  
  32. for raw_node in raw_nodes {
  33. let node = Node {
  34. id: raw_node.id,
  35. next: Cell::new(None)
  36. };
  37. nodes.insert(node.id, node);
  38. }
  39.  
  40. for raw_node in raw_nodes {
  41. let node = nodes.get(&raw_node.id).unwrap();
  42. let next = nodes.get(&raw_node.next).unwrap();
  43.  
  44. node.next.set(Some(next));
  45. }
  46.  
  47. nodes
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement