Guest User

Untitled

a guest
Jan 16th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #[derive(Clone, Default)]
  2. pub struct Cactus<T> {
  3. node: Option<Rc<RefCell<Node<T>>>>
  4. }
  5.  
  6. #[derive(Clone)]
  7. pub struct Node<T> {
  8. val: Rc<RefCell<T>>,
  9. parent: Option<Rc<RefCell<Node<T>>>>,
  10. len: usize
  11. }
  12.  
  13. impl<T> Cactus<T> {
  14. pub fn new() -> Cactus<T> {
  15. Cactus { node: None }
  16. }
  17.  
  18. pub fn is_empty(&self) -> bool {
  19. self.node.is_none()
  20. }
  21.  
  22. pub fn len(&self) -> usize {
  23. self.node.as_ref().map_or(0, |x| x.borrow().len)
  24. }
  25.  
  26. pub fn child(&self, val: T) -> Cactus<T> {
  27.  
  28. Cactus {
  29. node: Some(Rc::new(RefCell::new(Node {
  30. val: Rc::new(RefCell::new(val)),
  31. parent: self.node.clone(),
  32. len: self.node.as_ref().map_or(1, |x| x.borrow().len + 1)
  33. })))
  34. }
  35. }
  36.  
  37. pub fn parent(&self) -> Option<Cactus<T>> {
  38. self.node.as_ref()
  39. .map(|n| Cactus { node: n.borrow().parent.clone() })
  40. }
  41.  
  42. pub fn val(&mut self) -> Option<Rc<RefCell<T>>> {
  43. self.node.map(|n| n.borrow_mut().val.clone())
  44. }
  45. }
Add Comment
Please, Sign In to add comment