链表

A linked list is also a linear data structure, and each element in the linked list is actually a separate object while all the objects are linked together by the reference filed in each element. In a doubly linked list, each node contains, besides the next node link, a second link field pointing to the previous node in the sequence. The two links may be called next and prev. And many modern operating systems use doubly linked lists to maintain references to active processes, threads and other dynamic objects.

Properties

  • Indexing O(n)
  • Insertion O(1)
    • Beginning O(1)
    • Middle (Indexing time+O(1))
    • End O(n)
  • Deletion O(1)
    • Beginning O(1)
    • Middle (Indexing time+O(1))
    • End O(n)
  • Search O(n)
  1. use std::fmt::{self, Display, Formatter};
  2. use std::ptr::NonNull;
  3. struct Node<T> {
  4. val: T,
  5. next: Option<NonNull<Node<T>>>,
  6. prev: Option<NonNull<Node<T>>>,
  7. }
  8. impl<T> Node<T> {
  9. fn new(t: T) -> Node<T> {
  10. Node {
  11. val: t,
  12. prev: None,
  13. next: None,
  14. }
  15. }
  16. }
  17. pub struct LinkedList<T> {
  18. length: u32,
  19. start: Option<NonNull<Node<T>>>,
  20. end: Option<NonNull<Node<T>>>,
  21. }
  22. impl<T> Default for LinkedList<T> {
  23. fn default() -> Self {
  24. Self::new()
  25. }
  26. }
  27. impl<T> LinkedList<T> {
  28. pub fn new() -> Self {
  29. Self {
  30. length: 0,
  31. start: None,
  32. end: None,
  33. }
  34. }
  35. pub fn add(&mut self, obj: T) {
  36. let mut node = Box::new(Node::new(obj));
  37. // Since we are adding node at the end, next will always be None
  38. node.next = None;
  39. node.prev = self.end;
  40. // Get a pointer to node
  41. let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) });
  42. match self.end {
  43. // This is the case of empty list
  44. None => self.start = node_ptr,
  45. Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr },
  46. }
  47. self.end = node_ptr;
  48. self.length += 1;
  49. }
  50. pub fn get(&mut self, index: i32) -> Option<&T> {
  51. self.get_ith_node(self.start, index)
  52. }
  53. fn get_ith_node(&mut self, node: Option<NonNull<Node<T>>>, index: i32) -> Option<&T> {
  54. match node {
  55. None => None,
  56. Some(next_ptr) => match index {
  57. 0 => Some(unsafe { &(*next_ptr.as_ptr()).val }),
  58. _ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1),
  59. },
  60. }
  61. }
  62. }
  63. impl<T> Display for LinkedList<T>
  64. where
  65. T: Display,
  66. {
  67. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  68. match self.start {
  69. Some(node) => write!(f, "{}", unsafe { node.as_ref() }),
  70. None => Ok(()),
  71. }
  72. }
  73. }
  74. impl<T> Display for Node<T>
  75. where
  76. T: Display,
  77. {
  78. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  79. match self.next {
  80. Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }),
  81. None => write!(f, "{}", self.val),
  82. }
  83. }
  84. }
  85. #[cfg(test)]
  86. mod tests {
  87. use super::LinkedList;
  88. #[test]
  89. fn create_numeric_list() {
  90. let mut list = LinkedList::<i32>::new();
  91. list.add(1);
  92. list.add(2);
  93. list.add(3);
  94. println!("Linked List is {}", list);
  95. assert_eq!(3, list.length);
  96. }
  97. #[test]
  98. fn create_string_list() {
  99. let mut list_str = LinkedList::<String>::new();
  100. list_str.add("A".to_string());
  101. list_str.add("B".to_string());
  102. list_str.add("C".to_string());
  103. println!("Linked List is {}", list_str);
  104. assert_eq!(3, list_str.length);
  105. }
  106. #[test]
  107. fn get_by_index_in_numeric_list() {
  108. let mut list = LinkedList::<i32>::new();
  109. list.add(1);
  110. list.add(2);
  111. println!("Linked List is {}", list);
  112. let retrived_item = list.get(1);
  113. assert!(retrived_item.is_some());
  114. assert_eq!(2 as i32, *retrived_item.unwrap());
  115. }
  116. #[test]
  117. fn get_by_index_in_string_list() {
  118. let mut list_str = LinkedList::<String>::new();
  119. list_str.add("A".to_string());
  120. list_str.add("B".to_string());
  121. println!("Linked List is {}", list_str);
  122. let retrived_item = list_str.get(1);
  123. assert!(retrived_item.is_some());
  124. assert_eq!("B", *retrived_item.unwrap());
  125. }
  126. }