offset_linked_list.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. use std::mem::MaybeUninit;
  2. struct Node<T> {
  3. prev: usize,
  4. succ: usize,
  5. data: MaybeUninit<T>,
  6. }
  7. impl<T> Default for Node<T> {
  8. fn default() -> Self {
  9. Self {
  10. prev: 0,
  11. succ: 0,
  12. data: MaybeUninit::uninit(),
  13. }
  14. }
  15. }
  16. pub struct OffsetLinkedList<T> {
  17. nodes: Vec<Node<T>>,
  18. }
  19. #[derive(Copy, Clone, Eq, PartialEq)]
  20. pub struct NodeRef(pub usize);
  21. impl NodeRef {
  22. fn from_index(index: usize) -> Option<Self> {
  23. if index == OffsetLinkedList::<()>::HEAD {
  24. None
  25. } else {
  26. Some(Self(index - 1))
  27. }
  28. }
  29. }
  30. pub struct Iter<'a, T> {
  31. list: &'a OffsetLinkedList<T>,
  32. index: usize,
  33. }
  34. impl<'a, T> Iterator for Iter<'a, T> {
  35. type Item = &'a T;
  36. fn next(&mut self) -> Option<Self::Item> {
  37. if self.index == OffsetLinkedList::<()>::HEAD {
  38. None
  39. } else {
  40. let node = self.list.at(self.index);
  41. self.index = node.succ;
  42. Some(unsafe { &*node.data.as_ptr() })
  43. }
  44. }
  45. }
  46. impl<T> OffsetLinkedList<T> {
  47. const HEAD: usize = 0;
  48. pub fn create(data: Vec<T>) -> Self {
  49. let len = data.len();
  50. let mut nodes = Vec::with_capacity(len + 1);
  51. for _ in 0..len + 1 {
  52. nodes.push(Node::default());
  53. }
  54. for (i, data) in data.into_iter().enumerate() {
  55. nodes[i].succ = i + 1;
  56. nodes[i + 1].prev = i;
  57. nodes[i + 1].data = MaybeUninit::new(data);
  58. }
  59. nodes[Self::HEAD].prev = len;
  60. nodes[len].succ = Self::HEAD;
  61. Self { nodes }
  62. }
  63. fn offset_index(&self, index: NodeRef) -> usize {
  64. assert!(index.0 + 1 < self.nodes.len());
  65. index.0 + 1
  66. }
  67. pub fn lift(&mut self, index: NodeRef) {
  68. let index = self.offset_index(index);
  69. let prev = self.nodes[index].prev;
  70. let succ = self.nodes[index].succ;
  71. self.nodes[prev].succ = succ;
  72. self.nodes[succ].prev = prev;
  73. }
  74. pub fn unlift(&mut self, index: NodeRef) {
  75. let index = self.offset_index(index);
  76. let prev = self.nodes[index].prev;
  77. let succ = self.nodes[index].succ;
  78. self.nodes[prev].succ = index;
  79. self.nodes[succ].prev = index;
  80. }
  81. pub fn get(&self, index: NodeRef) -> &T {
  82. let index = self.offset_index(index);
  83. unsafe { &*self.nodes[index].data.as_ptr() }
  84. }
  85. #[allow(dead_code)]
  86. pub fn prev(&self, index: NodeRef) -> Option<NodeRef> {
  87. let index = self.offset_index(index);
  88. let succ = self.nodes[index].prev;
  89. NodeRef::from_index(succ)
  90. }
  91. pub fn succ(&self, index: NodeRef) -> Option<NodeRef> {
  92. let index = self.offset_index(index);
  93. NodeRef::from_index(self.nodes[index].succ)
  94. }
  95. pub fn first(&self) -> Option<NodeRef> {
  96. NodeRef::from_index(self.nodes[Self::HEAD].succ)
  97. }
  98. #[allow(dead_code)]
  99. pub fn last(&self) -> Option<NodeRef> {
  100. NodeRef::from_index(self.nodes[Self::HEAD].prev)
  101. }
  102. pub fn is_empty(&self) -> bool {
  103. self.nodes[Self::HEAD].succ == Self::HEAD
  104. }
  105. fn at(&self, index: usize) -> &Node<T> {
  106. &self.nodes[index]
  107. }
  108. #[allow(dead_code)]
  109. pub fn iter(&self) -> Iter<'_, T> {
  110. Iter {
  111. list: self,
  112. index: 1,
  113. }
  114. }
  115. }
  116. #[cfg(test)]
  117. mod tests {
  118. use crate::offset_linked_list::{NodeRef, OffsetLinkedList};
  119. fn make_list() -> OffsetLinkedList<char> {
  120. let data: Vec<char> = ('a'..='z').collect();
  121. OffsetLinkedList::create(data)
  122. }
  123. fn assert_char_list_eq(list: &OffsetLinkedList<char>, ans: &str) {
  124. let mut list_str = String::new();
  125. let mut leg = list.first();
  126. while let Some(curr) = leg {
  127. list_str.push(*list.get(curr));
  128. leg = list.succ(curr);
  129. }
  130. assert_eq!(&list_str, ans);
  131. }
  132. #[test]
  133. fn linked_list() {
  134. let mut list = make_list();
  135. let data_str: String = ('a'..='z').collect();
  136. assert_char_list_eq(&list, &data_str);
  137. let mut leg = list.first().unwrap();
  138. for i in 0..10 {
  139. if i % 3 == 0 {
  140. list.lift(leg);
  141. }
  142. leg = list.succ(leg).unwrap();
  143. }
  144. list.lift(leg);
  145. assert_char_list_eq(&list, "bcefhilmnopqrstuvwxyz");
  146. list.unlift(NodeRef(0));
  147. list.unlift(NodeRef(3));
  148. list.unlift(NodeRef(10));
  149. assert_char_list_eq(&list, "abcdefhiklmnopqrstuvwxyz");
  150. }
  151. #[test]
  152. fn empty_linked_list() {
  153. let mut list = make_list();
  154. assert!(!list.is_empty());
  155. let mut leg = list.first();
  156. while let Some(curr) = leg {
  157. leg = list.succ(curr);
  158. list.lift(curr);
  159. }
  160. assert!(list.is_empty())
  161. }
  162. #[test]
  163. fn iterate_linked_list() {
  164. let list_str: String = make_list().iter().collect();
  165. let data_str: String = ('a'..='z').collect();
  166. assert_eq!(data_str, list_str);
  167. }
  168. }