logo
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/// A singly-linked list with owned nodes.
///
/// This implementation is a simplified version of `std::forward_list` in C++.
///
/// References:
///
/// - [Rust Standard Library: std::collections::LinkedList][1]
/// - [Learning Rust With Entirely Too Many Linked Lists][2]
/// - [Stack Overflow: Deleting a node from singly linked list ...][3]
/// - [Stack Exchange: Reversal of a singly-linked list in Rust][4]
///
/// [1]: https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html
/// [2]: http://cglab.ca/~abeinges/blah/too-many-lists/book/README.html
/// [3]: https://stackoverflow.com/questions/51134192/
/// [4]: https://codereview.stackexchange.com/questions/150906
// ANCHOR: list_layout
pub struct SinglyLinkedList<T> {
    head: Option<Box<Node<T>>>,
}
// ANCHOR_END: list_layout

/// An owning iterator over the elements of a [`SinglyLinkedList`].
///
/// This struct is created by the `into_iter` method on [`SinglyLinkedList`].
// ANCHOR: IntoIter_layout
pub struct IntoIter<T>(SinglyLinkedList<T>);
// ANCHOR_END: IntoIter_layout

/// A immutable iterator over the elements of a [`SinglyLinkedList`].
///
/// This struct is created by the `iter` method on [`SinglyLinkedList`].
// ANCHOR: Iter_layout
pub struct Iter<'a, T> {
    next: Option<&'a Node<T>>, // 1
}
// ANCHOR_END: Iter_layout

/// A mutable iterator over the elements of a [`SinglyLinkedList`].
///
/// This struct is created by the `iter_mut` method on [`SinglyLinkedList`].
// ANCHOR: IterMut_layout
pub struct IterMut<'a, T> {
    next: Option<&'a mut Node<T>>,
}
// ANCHOR_END: IterMut_layout

/// Internal node representation.
#[derive(Debug)]
// ANCHOR: node_layout
struct Node<T> {
    elem: T,
    next: Option<Box<Node<T>>>,
}
// ANCHOR_END: node_layout

impl<T> SinglyLinkedList<T> {
    /// Constructs a new, empty `SinglyLinkedList<T>`.
    ///
    /// The list will not allocate until elements are pushed onto it.
    // ANCHOR: list_new
    pub fn new() -> Self {
        Self { head: None }
    }
    // ANCHOR_END: list_new

    /// Prepends the given element value to the beginning of the container.
    ///
    /// # Parameters
    ///
    /// * `elem` - The element to prepend.
    ///
    /// # Complexity
    ///
    /// Constant.
    // ANCHOR: list_push_front
    pub fn push_front(&mut self, elem: T) {
        let next = self.head.take(); // 1
        self.head = Some(Box::new(Node { elem, next })); // 2
    }
    // ANCHOR_END: list_push_front

    /// Removes and returns the first element of the container.
    /// If there are no elements in the container, return `None`.
    ///
    /// # Complexity
    ///
    /// Constant.
    // ANCHOR: list_pop_front
    pub fn pop_front(&mut self) -> Option<T> {
        // Take ownership of head
        let head = self.head.take()?; // 1
        self.head = head.next; // 2
        Some(head.elem) // 3
    }
    // ANCHOR_END: list_pop_front

    /// Inserts an element after the specified position in the container.
    ///
    /// If the position is out of bound, returns an `Result:Err` with the
    /// size of the list.
    ///
    /// # Parameters
    ///
    /// * `pos` - The index after which the element will be inserted.
    /// * `elem` - The element to be inserted.
    ///
    /// # Complexity
    ///
    /// Search time O(n) + O(1).
    // ANCHOR: list_insert_after
    pub fn insert_after(&mut self, pos: usize, elem: T) -> Result<(), usize> {
        let mut curr = &mut self.head;
        let mut pos_ = pos;

        // Find the node at `pos`.
        while pos_ > 0 {
            // 1
            curr = match curr.as_mut() {
                Some(node) => &mut node.next,
                None => return Err(pos - pos_),
            };
            pos_ -= 1;
        }

        // Take the ownership of current node.
        match curr.take() {
            // 2
            Some(mut node) => {
                // Node A
                // Create new node.
                let new_node = Box::new(Node {
                    // 3: Node B
                    elem,
                    next: node.next,
                });
                // Re-link new node and current node.
                node.next = Some(new_node); // 4

                // Assign current node back to the list.
                *curr = Some(node); // 5
            }
            None => return Err(pos - pos_),
        }
        Ok(())
    }
    // ANCHOR_END: list_insert_after

    /// Removes and returns an element at specified position from the container.
    ///
    /// # Parameters
    ///
    /// * `pos` - The index at which the element will be moved.
    ///
    /// # Complexity
    ///
    /// Search time O(n) + constant.
    // ANCHOR: list_remove
    pub fn remove(&mut self, pos: usize) -> Option<T> {
        let mut curr = &mut self.head;
        let mut pos = pos;

        // Find the node at `pos`.
        while pos > 0 {
            // 1
            curr = &mut curr.as_mut()?.next;
            pos -= 1;
        }

        // Assign next node to previous node.next pointer.
        let node = curr.take()?; // 2: Node A
        *curr = node.next; // 3: node.next is Node B
        Some(node.elem) // 4
    }
    // ANCHOR_END: list_remove

    /// Removes all elements from the container.
    ///
    /// # Complexity
    ///
    /// Linear in the size of the container.
    pub fn clear(&mut self) {
        *self = Self::new();
    }

    ///	Checks whether the container is empty.
    ///
    /// # Complexity
    ///
    /// Constant.
    pub fn is_empty(&self) -> bool {
        self.head.is_none()
    }

    /// Gets the number of elements in the container.
    ///
    /// # Complexity
    ///
    /// Linear in the size of the container.
    pub fn len(&self) -> usize {
        self.iter().count()
    }

    /// Reverses the order of the elements in the container.
    ///
    /// # Complexity
    ///
    /// Linear in the size of the container.
    // ANCHOR: list_reverse
    pub fn reverse(&mut self) {
        let mut prev = None; // 1: prev -> Node P
        let mut curr = self.head.take(); // 2
        while let Some(mut node) = curr {
            // 3: node -> Node A
            let next = node.next; // 3-1: next -> Node B
            node.next = prev.take(); // 3-2: Take ownership from previous node.
            prev = Some(node); // 3-3: Transfer ownership from current node to previous.
            curr = next; // 3-4: curr references to next node for next iteration.
        }
        self.head = prev.take(); // 4
    }
    // ANCHOR_END: list_reverse

    /// Creates an iterator that yields immutable reference of each element.
    // ANCHOR: list_iter
    pub fn iter(&self) -> Iter<T> {
        // 4
        Iter {
            next: self.head.as_deref(), // 5
        }
    }
    // ANCHOR_END: list_iter

    /// Creates an iterator that yields mutable reference of each element.
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut {
            next: self.head.as_deref_mut(),
        }
    }
}

// ANCHOR: list_drop
impl<T> Drop for SinglyLinkedList<T> {
    fn drop(&mut self) {
        let mut link = self.head.take(); // 1
        while let Some(mut node) = link {
            // 2
            link = node.next.take(); // 3: Take ownership of next `link` here.
        }
        // 4: Previous `node` goes out of scope and gets dropped here.
    }
}
// ANCHOR_END: list_drop

// ANCHOR: Iter
impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T; // 2

    fn next(&mut self) -> Option<Self::Item> {
        let node = self.next?;
        self.next = node.next.as_deref(); // 3
        Some(&node.elem)
    }
}
// ANCHOR_END: Iter

// ANCHOR: IterMut
impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        let node = self.next.take()?;
        self.next = node.next.as_deref_mut();
        Some(&mut node.elem)
    }
}
// ANCHOR_END: IterMut

// ANCHOR: IntoIter
impl<T> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop_front()
    }
}
// ANCHOR_END: IntoIter

// ANCHOR: IntoIterator
impl<T> IntoIterator for SinglyLinkedList<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    /// Creates a consuming iterator, that is, one that moves each value out of
    /// the list (from start to end). The list cannot be used after calling this.
    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self)
    }
}
// ANCHOR_END: IntoIterator

// ANCHOR: PartialEq
impl<T: PartialEq> PartialEq for SinglyLinkedList<T> {
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }
        self.iter().zip(other.iter()).all(|pair| pair.0 == pair.1)
    }
}
// ANCHOR_END: PartialEq

// ANCHOR: Debug
impl<T: std::fmt::Debug> std::fmt::Debug for SinglyLinkedList<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for node in self.iter() {
            write!(f, "{:?} -> ", node)?
        }
        Ok(())
    }
}
// ANCHOR_END: Debug

#[cfg(test)]
mod tests {
    use super::SinglyLinkedList;

    #[test]
    fn basics() {
        let mut l = SinglyLinkedList::<()>::new();
        assert_eq!(l.len(), 0);
        assert_eq!(l.pop_front(), None);
        assert_eq!(l.len(), 0);
        assert!(l.is_empty());
    }

    #[test]
    fn push_pop() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);

        // Check length and emptiness.
        assert_eq!(l.len(), 3);
        assert!(!l.is_empty());

        // Check removal.
        assert_eq!(l.pop_front(), Some(3));

        // Push more element to check popping correctly.
        l.push_front(4);
        l.push_front(5);
        assert_eq!(l.len(), 4);
        assert_eq!(l.pop_front(), Some(5));
        assert_eq!(l.pop_front(), Some(4));

        // Pop all elements to check exhaustion.
        assert_eq!(l.pop_front(), Some(2));
        assert_eq!(l.pop_front(), Some(1));
        assert_eq!(l.pop_front(), None);
        assert_eq!(l.len(), 0);

        // Check clear works.
        l.push_front(6);
        l.push_front(7);
        l.clear();
        assert!(l.is_empty());
    }

    #[test]
    fn reverse() {
        let mut l = SinglyLinkedList::<()>::new();
        // 0 elements without crash;
        l.reverse();
        let res = SinglyLinkedList::new();
        assert!(l == res);

        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.reverse();
        let mut res = SinglyLinkedList::new();
        res.push_front(1);
        assert!(l == res);

        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.reverse();
        let mut res = SinglyLinkedList::new();
        res.push_front(2);
        res.push_front(1);
        assert!(l == res);

        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);
        l.reverse();
        let mut res = SinglyLinkedList::new();
        res.push_front(3);
        res.push_front(2);
        res.push_front(1);
        assert!(l == res);
    }

    #[test]
    fn iter() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);

        let mut it = l.iter();
        assert_eq!(it.next(), Some(&3));
        assert_eq!(it.next(), Some(&2));
        assert_eq!(it.next(), Some(&1));
    }

    #[test]
    fn iter_mut() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);

        for elem in l.iter_mut() {
            *elem *= *elem;
        }

        let mut res = SinglyLinkedList::new();
        res.push_front(1);
        res.push_front(4);
        res.push_front(9);
        assert_eq!(l, res);
    }

    #[test]
    fn into_iter() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);

        // 3. `into_iter`
        let collected = l.into_iter().collect::<Vec<i32>>();
        assert_eq!(vec![3, 2, 1], collected);
        // Cannot access `l`. Value moved into `collected`.
    }

    #[test]
    fn insert() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);

        // Out of bound! Return the size of the list.
        assert_eq!(l.insert_after(3, 10).unwrap_err(), 3);

        // Insertion succeeded.
        assert!(l.insert_after(0, 10).is_ok());

        let mut res = SinglyLinkedList::new();
        res.push_front(1);
        res.push_front(2);
        res.push_front(10);
        res.push_front(3);
        assert_eq!(l, res);

        // Insertion succeeded again.
        assert!(l.insert_after(3, 11).is_ok());

        let mut res = SinglyLinkedList::new();
        res.push_front(11);
        res.push_front(1);
        res.push_front(2);
        res.push_front(10);
        res.push_front(3);
        assert_eq!(l, res);
    }

    #[test]
    fn remove() {
        let mut l = SinglyLinkedList::new();
        l.push_front(1);
        l.push_front(2);
        l.push_front(3);
        assert!(l.remove(5).is_none());
        assert_eq!(l.remove(1), Some(2));

        // Check remain list is in correct form.
        let mut res = SinglyLinkedList::new();
        res.push_front(1);
        res.push_front(3);
        assert_eq!(l, res);

        // Remove all elements
        assert_eq!(l.remove(1), Some(1));
        assert_eq!(l.remove(0), Some(3));
    }
}