Guest User

Untitled

a guest
Oct 21st, 2019
77
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::mem;
  2.  
  3. struct Node<T> {
  4. data: T,
  5. next: Option<Box<Node<T>>>,
  6. }
  7.  
  8. pub struct SimpleLinkedList<T> {
  9. head: Option<Box<Node<T>>>,
  10. }
  11.  
  12. impl<T> SimpleLinkedList<T> {
  13. pub fn new() -> Self {
  14. SimpleLinkedList {head: None}
  15. }
  16.  
  17. pub fn len(&self) -> usize {
  18. let mut l = 0;
  19. let mut temp = self.head.as_ref();
  20. while temp.is_some() {
  21. l+=1;
  22. temp = temp.unwrap().next.as_ref();
  23. }
  24. l
  25. }
  26.  
  27. pub fn push(&mut self, _element: T) {
  28. let new_node = Box::new(Node {
  29. data: _element,
  30. next: mem::replace(&mut self.head, None),
  31. });
  32.  
  33. self.head = Some(new_node);
  34. }
  35.  
  36. pub fn pop(&mut self) -> Option<T> {
  37. match mem::replace(&mut self.head, None) {
  38. None => None,
  39. Some(node) => {
  40. self.head = node.next;
  41. Some(node.data)
  42. }
  43. }
  44. }
  45.  
  46. pub fn peek(&self) -> Option<&T> {
  47. Some(&self.head.as_ref().unwrap().data)
  48. }
  49. }
  50.  
  51. impl<T: Clone> SimpleLinkedList<T> {
  52. pub fn rev(&self) -> SimpleLinkedList<T> {
  53. let mut temp = SimpleLinkedList {head: None};
  54. while self.head.is_some() {
  55. let t = self.pop().unwrap();
  56. let new_node = Box::new(Node {
  57. data: t.clone(),
  58. next: mem::replace(&mut temp.head, None),
  59. });
  60.  
  61. temp.head = Some(new_node);
  62. }
  63. temp
  64. }
  65. }
  66.  
  67. impl<'a, T: Clone> From<&'a [T]> for SimpleLinkedList<T> {
  68. fn from(_item: &[T]) -> Self {
  69. let mut temp = SimpleLinkedList::new();
  70. for i in _item {
  71. temp.push(i.clone());
  72. }
  73. temp
  74. }
  75. }
  76.  
  77. impl<T> Into<Vec<T>> for SimpleLinkedList<T> {
  78. fn into(self) -> Vec<T> {
  79. vec![]
  80. }
  81. }
RAW Paste Data