I am trying to create a singly linked list composed of nodes each having a reference to the next node, data associated with the node and, this is the interesting bit, a reference to a random node in the list. The random node of a given node can appear before the node itself or after it in the list. The random node is optional. Here is a diagram:
+---------+ +-------------------+
| v v |
+-+--+ ++--++ +----+ +-+--+
+--->+Data+---->+Data+---->+Data+---->+Data|
+-+--+ +----+ +--+-+ +----+
^ |
+----------------------+
The diagram demonstrates a list with four nodes. The random reference of the first node points to the second node. The second node's random reference is missing. The random reference of the third node is to the first one. The random reference of the forth node points to the second one.
The list needs to support only adding new nodes. Once a node has been added it lives as long as the list so random references cannot get invalidated by removing a node.
What I tried:
I am stuck at the absolute beginning - I cannot figure out how to design the struct and how to construct the list. Here is the code I ended up with after wrestling with the compiler for a while:
type NodePtr<'a, T> = Option<Box<Node<'a, T>>>;
pub struct Node<'a, T: 'a> {
data: T,
next: NodePtr<'a, T>,
random: Option<&'a Node<'a, T>>,
}
pub struct List<'a, T: 'a> {
root: NodePtr<'a, T>,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn construct() {
let mut list:List<i32> = List {root: Some(Box::new(Node {data: 5, next: None, random: None}))};
let mut f: &mut Node<i32> = &mut **list.root.as_mut().unwrap();
f.random = Some(&f);
}
}
The compiles refuses to compile it with:
src/topology_copy.rs:21:26: 21:27 error: `f` does not live long enough
src/topology_copy.rs:21 f.random = Some(&f);
And the code is very messy. Obviously I am doing it wrong.