data_structures/linked_list/
linked_list.rs

1use super::errors::*;
2use super::into_iter::*;
3use super::iter::*;
4use super::iter_mut::*;
5use super::node::*;
6
7#[derive(Debug)]
8pub struct LinkedList<T> {
9    head: Next<T>,
10    /// Get length of linked list
11    pub length: usize,
12}
13
14// MAIN
15impl<T> LinkedList<T> {
16    /// Get new LinkedList
17    pub fn new() -> Self {
18        LinkedList {
19            head: Box::new(None),
20            length: 0,
21        }
22    }
23}
24
25// INSERTION
26impl<T> LinkedList<T> {
27    /// Append to the end of the linked list.
28    ///
29    /// # Time Complexity
30    /// O(n)
31    ///
32    /// # Example
33    /// ```
34    ///# use self::linked_list_lib::linked_list::*;
35    ///  let mut linked_list = LinkedList::<i32>::new();
36    ///  linked_list.append(1);
37    ///  linked_list.append(2);
38    ///  linked_list.append(3);
39    ///
40    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 1 -> 2 -> 3 -> None");
41    /// ```
42    pub fn append(&mut self, data: T) {
43        self.length += 1;
44
45        let new_node = Some(Node::new(data));
46
47        let mut traverser = &mut self.head;
48
49        while let Some(ref mut node) = **traverser {
50            traverser = &mut (*node).next;
51        }
52
53        **traverser = new_node;
54    }
55
56    /// Insert elemet at posn in the linked list.
57    ///
58    /// # Time Complexity
59    /// O(posn)
60    ///
61    /// # Example
62    /// ```
63    ///# use self::linked_list_lib::linked_list::*;
64    ///  let mut linked_list = LinkedList::<i32>::new();
65    ///  linked_list.insert(44, 0);
66    ///  linked_list.insert(22, 0);
67    ///  linked_list.insert(33, 1);
68    ///
69    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 22 -> 33 -> 44 -> None");
70    /// ```
71    ///
72    /// # Errors
73    ///
74    /// The function returns Error::PositionOutOfBounds(posn, len)
75    /// if position to be inserted is >= linked list length.
76    pub fn insert(&mut self, data: T, posn: usize) -> Result<(), Error> {
77        self.length += 1;
78
79        let new_node = Some(Node::new(data));
80        let mut traverser = &mut self.head;
81        let mut counter: usize = 0;
82
83        while (**traverser).is_some() && counter < posn {
84            counter += 1;
85            traverser = &mut (**traverser).as_mut().unwrap().next;
86        }
87
88        if counter == posn {
89            let prev_val = std::mem::replace(&mut **traverser, new_node);
90            *((**traverser).as_mut().unwrap().next) = prev_val;
91            Ok(())
92        } else {
93            Err(Error::PositionOutOfBounds(posn, self.length))
94        }
95    }
96
97    /// Add element to the beginning of the linked list.
98    ///
99    /// # Time Complexity
100    /// O(1)
101    ///
102    /// # Example
103    /// ```
104    ///# use self::linked_list_lib::linked_list::*;
105    ///  let mut linked_list = LinkedList::<i32>::new();
106    ///  linked_list.prepend(3);
107    ///  linked_list.prepend(2);
108    ///  linked_list.prepend(1);
109    ///
110    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 1 -> 2 -> 3 -> None");
111    /// ```
112    pub fn prepend(&mut self, data: T) {
113        self.length += 1;
114
115        let new_node = Node::new(data);
116        let prev_val = std::mem::replace(&mut *self.head, Some(new_node));
117        if let Some(ref mut node) = *(self.head) {
118            *((*node).next) = prev_val;
119        }
120    }
121}
122
123// DELETION
124impl<T> LinkedList<T> {
125    /// Delete element at the given position.
126    ///
127    /// # Time Complexity
128    /// O(posn)
129    ///
130    /// # Example
131    /// ```
132    ///# use self::linked_list_lib::linked_list::*;
133    ///  let mut linked_list = LinkedList::<i32>::new();
134    ///  linked_list.append(1);
135    ///  linked_list.append(2);
136    ///  linked_list.append(3);
137    ///  linked_list.append(4);
138    ///
139    ///  linked_list.delete_at_posn(2);
140    ///
141    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 1 -> 2 -> 4 -> None");
142    /// ```
143    ///
144    /// # Errors
145    ///
146    /// The function returns Error::PositionOutOfBounds(posn, len)
147    /// if position to be deleted is >= linked list length.
148
149    pub fn delete_at_posn(&mut self, posn: usize) -> Result<(), Error> {
150        if posn >= (*self).length {
151            return Err(Error::PositionOutOfBounds(posn, (*self).length));
152        }
153
154        (*self).length -= 1;
155
156        let mut counter = 0;
157        let mut iter_mut = (*self).iter_mut();
158
159        while counter < posn {
160            counter += 1;
161            iter_mut.next();
162        }
163
164        iter_mut.0.map(|next| {
165            **next = match std::mem::replace(&mut (**next), None) {
166                Some(node) => *(node.next),
167                None => None,
168            };
169        });
170
171        Ok(())
172    }
173
174    /// Delete element at the given position.
175    ///
176    /// # Time Complexity
177    /// O(n)
178    ///
179    /// # Example
180    /// ```
181    ///# use self::linked_list_lib::linked_list::*;
182    ///  let mut linked_list = LinkedList::<i32>::new();
183    ///  linked_list.append(1);
184    ///  linked_list.append(2);
185    ///  linked_list.append(3);
186    ///  linked_list.append(4);
187    ///
188    ///  // delete first 2 elements
189    ///  let mut counter = 2;
190    ///  linked_list.delete_where(move |element| {
191    ///     counter -= 1;
192    ///     counter >= 0
193    ///  });
194    ///
195    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 3 -> 4 -> None");
196    ///
197    ///  linked_list.delete_where(|element| element % 2 == 0);
198    ///  
199    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 3 -> None");
200    /// ```
201    ///
202    /// # Errors
203    ///
204    /// The function returns Error::ElementDoesNotExist
205    /// if no element of linked list returns true with closure f.
206    pub fn delete_where<F: FnMut(&T) -> bool>(&mut self, mut f: F) -> Result<(), Error> {
207        let mut iter_mut = (*self).iter_mut();
208        let mut counter = 0;
209
210        loop {
211            // either the iterator contains None or iterator points to end element i.e. None
212            if iter_mut.0.is_none() || (**(iter_mut.0.as_ref().unwrap())).is_none() {
213                break;
214            }
215
216            let ref node_ref = *(***(iter_mut.0.as_ref().unwrap())).as_ref().unwrap();
217
218            if f(&(*node_ref).data) {
219                counter += 1;
220
221                let deleted_node =
222                    std::mem::replace(&mut (***(iter_mut.0.as_mut().unwrap())), None);
223                ***(iter_mut.0.as_mut().unwrap()) = *(deleted_node.unwrap().next);
224            } else {
225                iter_mut.next();
226            }
227        }
228
229        if counter == 0 {
230            Err(Error::ElementDoesNotExist)
231        } else {
232            (*self).length -= counter;
233            Ok(())
234        }
235    }
236}
237
238//OTHERS
239impl<T> LinkedList<T> {
240    /// Returns reversed linked list
241    ///
242    /// # Time Complexity
243    /// O(n)
244    ///
245    /// # Example
246    /// ```
247    ///# use self::linked_list_lib::linked_list::*;
248    ///  let mut linked_list = LinkedList::<i32>::new();
249    ///  linked_list.append(1);
250    ///  linked_list.append(2);
251    ///  linked_list.append(3);
252    ///  linked_list.append(4);
253    ///
254    ///  linked_list = linked_list.reverse();
255    ///
256    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 4 -> 3 -> 2 -> 1 -> None");
257    /// ```
258    pub fn reverse(self) -> LinkedList<T> {
259        let mut reversed_linked_list = LinkedList::<T>::new();
260
261        for element in self.into_iter() {
262            reversed_linked_list.prepend(element);
263        }
264
265        reversed_linked_list
266    }
267}
268
269// ITERATORS
270impl<T> LinkedList<T> {
271    /// Produces mutable iterator
272    ///
273    /// # Example
274    /// ```
275    ///# use self::linked_list_lib::linked_list::*;
276    ///  let mut linked_list = LinkedList::<i32>::new();
277    ///  linked_list.append(1);
278    ///  linked_list.append(2);
279    ///  linked_list.append(3);
280    ///  linked_list.append(4);
281    ///
282    ///  linked_list.iter_mut().for_each(|element| *element += 1);
283    ///
284    ///  assert_eq!(format!("{}", linked_list), "HEAD -> 2 -> 3 -> 4 -> 5 -> None");
285    /// ```
286    pub fn iter_mut(&mut self) -> IterMut<T> {
287        IterMut(Some(&mut (*self).head))
288    }
289
290    /// Produces am immutable iterator
291    ///
292    /// # Example
293    /// ```
294    ///# use self::linked_list_lib::linked_list::*;
295    ///  let mut linked_list = LinkedList::<i32>::new();
296    ///  linked_list.append(1);
297    ///  linked_list.append(2);
298    ///  linked_list.append(3);
299    ///
300    ///  let mut vector = Vec::new();
301    ///
302    ///  for element in linked_list.iter() {
303    ///     vector.push(*element);
304    ///  }
305    ///
306    ///  assert_eq!(vector, [1, 2, 3]);
307    /// ```
308    pub fn iter(&self) -> Iter<T> {
309        Iter(&(*self).head)
310    }
311
312    /// Consumes the linked list and gives an iterator.
313    ///
314    /// # Example
315    /// ```
316    ///# use self::linked_list_lib::linked_list::*;
317    ///  let mut linked_list = LinkedList::<i32>::new();
318    ///  linked_list.append(1);
319    ///  linked_list.append(2);
320    ///  linked_list.append(3);
321    ///
322    ///  let mut vector: Vec<i32> = linked_list.into_iter().collect();
323    ///
324    ///  assert_eq!(vector, [1, 2, 3]);
325    /// ```
326    pub fn into_iter(self) -> IntoIter<T> {
327        IntoIter(self.head)
328    }
329}