Skip to main content

plain_ds/lite/list/
single_linked_list.rs

1//! This module contains single-linked list implementation.
2
3use std::ptr;
4
5use anyhow::anyhow;
6
7use crate::lite::list::iter::{IntoIter, Iter, IterMut};
8use crate::lite::list::merge_sort::merge_sort;
9use crate::lite::list::node::Node;
10
11pub struct SingleLinkedList<T> {
12    head: *mut Node<T>, // 8 bytes
13    last: *mut Node<T>, // 8 bytes
14    size: usize,        // 8 bytes
15}
16
17impl<T> SingleLinkedList<T> {
18    /// Creates empty list.
19    pub fn new() -> Self {
20        Self {
21            head: ptr::null_mut(),
22            last: ptr::null_mut(),
23            size: 0,
24        }
25    }
26
27    /// Creates list from slice.
28    pub fn from_slice(slice: &[T]) -> Self
29    where
30        T: Clone,
31    {
32        let mut list = SingleLinkedList::new();
33        for value in slice {
34            list.push_back((*value).clone());
35        }
36        list
37    }
38
39    /// Collect list values into a vector.
40    /// Efficiency: O(n)
41    pub fn to_vec(&self) -> Vec<T>
42    where
43        T: Clone,
44    {
45        self.iter().map(|item| (*item).clone()).collect()
46    }
47
48    /// Returns list size.
49    /// Efficiency: O(1)
50    pub fn len(&self) -> usize {
51        self.size
52    }
53
54    /// Checks if the list is empty.
55    /// Efficiency: O(1)
56    pub fn is_empty(&self) -> bool {
57        self.size == 0
58    }
59
60    /// Returns the payload value of the first node in the list.
61    /// Efficiency: O(1)
62    pub fn head(&self) -> Option<&T> {
63        if self.head.is_null() {
64            None
65        } else {
66            Some(unsafe { &(*self.head).payload })
67        }
68    }
69
70    /// Returns the payload value of the last node in the list.
71    /// Efficiency: O(1)
72    pub fn last(&self) -> Option<&T> {
73        if self.last.is_null() {
74            None
75        } else {
76            Some(unsafe { &(*self.last).payload })
77        }
78    }
79
80    /// Returns a list item by index, or error if index out of bounds.
81    /// Efficiency: O(n)
82    pub fn get(&self, index: usize) -> anyhow::Result<&T> {
83        if index >= self.size {
84            return Err(anyhow!("index out of bounds"));
85        }
86        if index == 0 {
87            return self.head().ok_or(anyhow!("list is empty"));
88        }
89        if index + 1 == self.size {
90            return self.last().ok_or(anyhow!("list is empty"));
91        }
92
93        // Finding by index
94        self.iter().nth(index).ok_or(anyhow!("list is empty"))
95    }
96
97    /// Returns a mutable list item by index, or error if index out of bounds.
98    /// Efficiency: O(n)
99    pub fn get_mut(&mut self, index: usize) -> anyhow::Result<&mut T> {
100        if index >= self.size {
101            return Err(anyhow!("index out of bounds"));
102        }
103        if index == 0 {
104            return Ok(unsafe { &mut (*self.head).payload });
105        }
106        if index + 1 == self.size {
107            return Ok(unsafe { &mut (*self.last).payload });
108        }
109
110        // Finding by index
111        self.iter_mut().nth(index).ok_or(anyhow!("list is empty"))
112    }
113
114    /// Returns an iterator over the immutable items of the list.
115    pub fn iter(&self) -> impl Iterator<Item = &T> {
116        Iter::new(self.head)
117    }
118
119    /// Returns an iterator over the mutable items of the list.
120    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
121        IterMut::new(self.head)
122    }
123
124    /// Returns an iterator that consumes the list.
125    pub fn into_iter(self) -> impl Iterator<Item = T> {
126        IntoIter::new(self)
127    }
128
129    /// Adds a new node to the end of the list.
130    /// Efficiency: O(1)
131    pub fn push_back(&mut self, payload: T) {
132        let ptr = Box::into_raw(Box::new(Node::new(payload)));
133        if self.is_empty() {
134            self.head = ptr;
135        } else {
136            unsafe { (*self.last).next = ptr };
137        }
138        self.last = ptr;
139        self.size += 1;
140    }
141
142    /// Adds a new node to the front of the list.
143    /// Efficiency: O(1)
144    pub fn push_front(&mut self, payload: T) {
145        let ptr = Box::into_raw(Box::new(Node::new(payload)));
146        if self.is_empty() {
147            self.last = ptr;
148        } else {
149            unsafe { (*ptr).next = self.head }
150        }
151        self.head = ptr;
152        self.size += 1;
153    }
154
155    /// Removes a node from the end of the list and returns its payload value.
156    /// Efficiency: O(n)
157    pub fn pop_back(&mut self) -> Option<T> {
158        if self.is_empty() {
159            return None;
160        }
161
162        // Case: only one node in list
163        if self.head == self.last {
164            let payload = unsafe { Box::from_raw(self.head).payload };
165            self.head = ptr::null_mut();
166            self.last = ptr::null_mut();
167            self.size -= 1;
168            return Some(payload);
169        }
170
171        // Finding the penultimate node
172        let mut current = self.head;
173        unsafe {
174            while (*current).next != self.last {
175                current = (*current).next;
176            }
177        }
178
179        // current now points to the penultimate node
180        let old_last = self.last;
181        self.last = current;
182        unsafe { (*self.last).next = ptr::null_mut() };
183
184        // Release the last node and extract the payload
185        let payload = unsafe {
186            let boxed = Box::from_raw(old_last);
187            boxed.payload
188        };
189
190        self.size -= 1;
191        Some(payload)
192    }
193
194    /// Removes a node from the front of the list and returns its payload value.
195    /// Efficiency: O(1)
196    pub fn pop_front(&mut self) -> Option<T> {
197        if self.is_empty() {
198            return None;
199        }
200
201        let old_head = unsafe { Box::from_raw(self.head) };
202        self.head = old_head.next;
203        if self.len() == 1 {
204            self.last = ptr::null_mut();
205        }
206
207        self.size -= 1;
208        Some(old_head.payload)
209    }
210
211    /// Insert a new node at the specified location in the list.
212    /// Error returns, if the index out of bounds.
213    /// Efficiency: O(n)
214    pub fn insert(&mut self, index: usize, payload: T) -> anyhow::Result<()> {
215        if index > self.size {
216            return Err(anyhow!("index out of bounds"));
217        }
218        if index == self.size {
219            self.push_back(payload);
220            return Ok(());
221        }
222        if index == 0 {
223            self.push_front(payload);
224            return Ok(());
225        }
226
227        // Finding the insert point
228        let mut current = self.head;
229        let mut index = index;
230        unsafe {
231            while index > 1 {
232                current = (*current).next;
233                index -= 1;
234            }
235        }
236
237        let mut boxed = Box::new(Node::new(payload));
238        unsafe {
239            boxed.next = (*current).next;
240            (*current).next = Box::into_raw(boxed);
241        }
242
243        self.size += 1;
244        Ok(())
245    }
246
247    /// Removes a node from the specified location in the list.
248    /// Error returns, if the index out of bounds.
249    /// Efficiency: O(n)
250    pub fn remove(&mut self, index: usize) -> anyhow::Result<T> {
251        if index >= self.size {
252            return Err(anyhow!("index out of bounds"));
253        }
254        if index == 0 {
255            // remove first
256            return Ok(self.pop_front().unwrap());
257        }
258        if index + 1 == self.size {
259            // remove last
260            return Ok(self.pop_back().unwrap());
261        }
262
263        // Finding the removing item
264        let mut before = self.head;
265        let mut index = index;
266        unsafe {
267            while index > 1 {
268                before = (*before).next;
269                index -= 1;
270            }
271        }
272
273        let removed = unsafe { Box::from_raw((*before).next) };
274        unsafe { (*before).next = removed.next };
275
276        self.size -= 1;
277        Ok(removed.payload)
278    }
279
280    /// Removes all items from the list.
281    /// Efficiency: O(n)
282    pub fn clear(&mut self) {
283        while self.len() != 0 {
284            let _ = self.pop_front();
285        }
286    }
287
288    /// Finds the first node whose payload is equal to the given one and returns its index.
289    /// Returns `None` if there is no such node.
290    /// Efficiency: O(n)
291    pub fn find(&self, value: &T) -> Option<usize>
292    where
293        T: PartialEq,
294    {
295        self.find_if(|item| item == value)
296    }
297
298    /// Finds the first node whose payload satisfies the predicate and returns its index.
299    /// Returns `None` if there is no such node.
300    /// Efficiency: O(n)
301    pub fn find_if(&self, predicate: impl Fn(&T) -> bool) -> Option<usize>
302    where
303        T: PartialEq,
304    {
305        self.iter()
306            .enumerate()
307            .find(|(_, item)| predicate(*item))
308            .map(|(index, _)| index)
309    }
310
311    /// Sorts the list in ascending order using merge sort algorithm.
312    /// Efficiency: O(n log n)
313    /// Space complexity: O(log n) due to recursion stack
314    pub fn sort(&mut self)
315    where
316        T: PartialOrd + Default,
317    {
318        if self.size <= 1 {
319            return; // Already sorted
320        }
321
322        // Extract the head and reset the list
323        let head = self.head;
324        self.head = ptr::null_mut();
325        self.last = ptr::null_mut();
326        self.size = 0;
327
328        // Sort the extracted nodes and get new head
329        let sorted_head = merge_sort(head);
330
331        // Reconstruct the list with sorted nodes
332        self.rebuild_from_sorted_list(sorted_head);
333    }
334
335    /// Rebuilds the SingleLinkedList from a sorted list of nodes
336    fn rebuild_from_sorted_list(&mut self, head: *mut Node<T>) {
337        self.head = head;
338        self.size = 0;
339
340        if head.is_null() {
341            self.last = std::ptr::null_mut();
342            return;
343        }
344
345        // Traverse to find the last node and count size
346        let mut current = head;
347        self.size = 1;
348
349        unsafe {
350            while !(*current).next.is_null() {
351                current = (*current).next;
352                self.size += 1;
353            }
354            self.last = current;
355        }
356    }
357}
358
359impl<T> Drop for SingleLinkedList<T> {
360    fn drop(&mut self) {
361        use std::mem::ManuallyDrop;
362
363        let mut current = ManuallyDrop::new(self.head);
364        while !current.is_null() {
365            unsafe {
366                let node = Box::from_raw(ManuallyDrop::take(&mut current));
367                current = ManuallyDrop::new(node.next);
368            }
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    // Helper function to create a list with values [0, 1, 2, ..., n-1]
378    fn setup_list(n: usize) -> SingleLinkedList<usize> {
379        let mut list = SingleLinkedList::new();
380        for i in 0..n {
381            list.push_back(i);
382        }
383        list
384    }
385
386    #[test]
387    fn test_creation() {
388        let list: SingleLinkedList<u8> = SingleLinkedList::new();
389        assert_eq!(list.len(), 0, "not zero length after creation");
390        assert_eq!(list.head(), None, "not empty head after creation");
391        assert_eq!(list.last(), None, "not empty last after creation");
392        assert!(list.is_empty(), "is_empty() returns `false` after creation");
393
394        let list: SingleLinkedList<String> = SingleLinkedList::new();
395        assert!(list.is_empty(), "is_empty() returns `false` after creation");
396
397        let list: SingleLinkedList<&[char]> = SingleLinkedList::new();
398        assert!(list.is_empty(), "is_empty() returns `false` after creation");
399    }
400
401    mod get {
402        use super::*;
403
404        #[test]
405        fn test_get_empty_list() {
406            let list: SingleLinkedList<i32> = SingleLinkedList::new();
407            assert!(
408                list.get(0).is_err(),
409                "get() on empty list should return error"
410            );
411            assert!(
412                list.get(1).is_err(),
413                "get() with any index on empty list should return error"
414            );
415        }
416
417        #[test]
418        fn test_get_index_out_of_bounds() {
419            let mut list = SingleLinkedList::new();
420            list.push_back(10);
421            list.push_back(20);
422            list.push_back(30);
423
424            assert!(
425                list.get(3).is_err(),
426                "get() with index == size should return error (out of bounds)"
427            );
428            assert!(
429                list.get(4).is_err(),
430                "get() with index > size should return error"
431            );
432            assert!(
433                list.get(100).is_err(),
434                "get() with large out-of-bounds index should return error"
435            );
436        }
437
438        #[test]
439        fn test_get_first_element() {
440            let mut list = SingleLinkedList::new();
441            list.push_back(100);
442            list.push_back(200);
443            list.push_back(300);
444
445            let result = list.get(0).unwrap();
446            assert_eq!(*result, 100, "get(0) should return first element (100)");
447        }
448
449        #[test]
450        fn test_get_last_element() {
451            let mut list = SingleLinkedList::new();
452            list.push_back(100);
453            list.push_back(200);
454            list.push_back(300);
455
456            let result = list.get(2).unwrap(); // index = size - 1
457            assert_eq!(
458                *result, 300,
459                "get(last_index) should return last element (300)"
460            );
461        }
462
463        #[test]
464        fn test_get_middle_element() {
465            let mut list = SingleLinkedList::new();
466            list.push_back(10);
467            list.push_back(20);
468            list.push_back(30);
469            list.push_back(40);
470            list.push_back(50);
471
472            let result = list.get(2).unwrap(); // middle element
473            assert_eq!(*result, 30, "get(2) should return middle element (30)");
474
475            let result2 = list.get(1).unwrap();
476            assert_eq!(*result2, 20, "get(1) should return second element (20)");
477        }
478
479        #[test]
480        fn test_get_single_element_list() {
481            let mut list = SingleLinkedList::new();
482            list.push_back(42);
483
484            let result = list.get(0).unwrap();
485            assert_eq!(
486                *result, 42,
487                "get(0) on single-element list should return that element"
488            );
489
490            assert!(
491                list.get(1).is_err(),
492                "get(1) on single-element list should be out of bounds"
493            );
494        }
495
496        #[test]
497        fn test_get_with_complex_types() {
498            // Test with String
499            let mut string_list = SingleLinkedList::new();
500            string_list.push_back("apple".to_string());
501            string_list.push_back("banana".to_string());
502            string_list.push_back("cherry".to_string());
503
504            let first = string_list.get(0).unwrap();
505            assert_eq!(first, "apple", "get(0) should return 'apple'");
506
507            let last = string_list.get(2).unwrap();
508            assert_eq!(last, "cherry", "get(2) should return 'cherry'");
509
510            // Test with Vec
511            let mut vec_list = SingleLinkedList::new();
512            vec_list.push_back(vec![1, 2]);
513            vec_list.push_back(vec![3, 4]);
514
515            let vec_result = vec_list.get(1).unwrap();
516            assert_eq!(vec_result, &vec![3, 4], "get(1) should return vec![3, 4]");
517        }
518
519        #[test]
520        fn test_get_preserves_list_integrity() {
521            let mut list = SingleLinkedList::new();
522            list.push_back(1);
523            list.push_back(2);
524            list.push_back(3);
525
526            // Get element in the middle
527            let _ = list.get(1).unwrap();
528
529            // Verify list is unchanged
530            assert_eq!(
531                list.len(),
532                3,
533                "list length should remain unchanged after get()"
534            );
535            assert_eq!(list.head(), Some(&1), "head should remain the same");
536            assert_eq!(list.last(), Some(&3), "last should remain the same");
537
538            // Verify we can still get other elements
539            assert_eq!(
540                *list.get(0).unwrap(),
541                1,
542                "get(0) after get(1) should still work"
543            );
544            assert_eq!(
545                *list.get(2).unwrap(),
546                3,
547                "get(2) after get(1) should still work"
548            );
549        }
550
551        #[test]
552        fn test_get_mut_empty_list() {
553            let mut list: SingleLinkedList<i32> = SingleLinkedList::new();
554            assert!(
555                list.get_mut(0).is_err(),
556                "get_mut() on empty list should return error"
557            );
558        }
559
560        #[test]
561        fn test_get_mut_index_out_of_bounds() {
562            let mut list = SingleLinkedList::new();
563            list.push_back(10);
564            list.push_back(20);
565
566            assert!(
567                list.get_mut(2).is_err(),
568                "get_mut() with index == size should return error"
569            );
570            assert!(
571                list.get_mut(5).is_err(),
572                "get_mut() with large out-of-bounds index should return error"
573            );
574        }
575
576        #[test]
577        fn test_get_mut_first_element() {
578            let mut list = SingleLinkedList::new();
579            list.push_back(100);
580            list.push_back(200);
581            list.push_back(300);
582
583            let mut_ref = list.get_mut(0).unwrap();
584            *mut_ref = 999;
585
586            assert_eq!(
587                *list.get(0).unwrap(),
588                999,
589                "first element should be modified to 999"
590            );
591            assert_eq!(
592                *list.head().unwrap(),
593                999,
594                "head should reflect the modification"
595            );
596        }
597
598        #[test]
599        fn test_get_mut_last_element() {
600            let mut list = SingleLinkedList::new();
601            list.push_back(100);
602            list.push_back(200);
603            list.push_back(300);
604
605            let mut_ref = list.get_mut(2).unwrap(); // last element
606            *mut_ref = 888;
607
608            assert_eq!(
609                *list.get(2).unwrap(),
610                888,
611                "last element should be modified to 888"
612            );
613            assert_eq!(
614                *list.last().unwrap(),
615                888,
616                "last should reflect the modification"
617            );
618        }
619
620        #[test]
621        fn test_get_mut_middle_element() {
622            let mut list = SingleLinkedList::new();
623            list.push_back(10);
624            list.push_back(20);
625            list.push_back(30);
626            list.push_back(40);
627
628            let mut_ref = list.get_mut(2).unwrap(); // third element
629            *mut_ref *= 2; // 30 * 2 = 60
630
631            assert_eq!(
632                *list.get(2).unwrap(),
633                60,
634                "middle element should be doubled to 60"
635            );
636        }
637
638        #[test]
639        fn test_get_mut_single_element_list() {
640            let mut list = SingleLinkedList::new();
641            list.push_back(42);
642
643            let mut_ref = list.get_mut(0).unwrap();
644            *mut_ref += 1;
645
646            assert_eq!(
647                *list.get(0).unwrap(),
648                43,
649                "single element should be modified to 43"
650            );
651        }
652
653        #[test]
654        fn test_get_mut_with_complex_types() {
655            // Test with String — modify by pushing more text
656            let mut string_list = SingleLinkedList::new();
657            string_list.push_back("hello".to_string());
658            string_list.push_back("world".to_string());
659
660            let mut_str = string_list.get_mut(0).unwrap();
661            mut_str.push_str(" there");
662
663            assert_eq!(
664                string_list.get(0).unwrap(),
665                "hello there",
666                "first string should be modified"
667            );
668
669            // Test with Vec — modify by adding elements
670            let mut vec_list = SingleLinkedList::new();
671            vec_list.push_back(vec![1, 2]);
672            vec_list.push_back(vec![3, 4]);
673
674            let mut_vec = vec_list.get_mut(1).unwrap();
675            mut_vec.push(5);
676
677            assert_eq!(
678                vec_list.get(1).unwrap(),
679                &vec![3, 4, 5],
680                "second vector should have new element"
681            );
682        }
683
684        #[test]
685        fn test_get_mut_preserves_list_integrity() {
686            let mut list = SingleLinkedList::new();
687            list.push_back(1);
688            list.push_back(2);
689            list.push_back(3);
690
691            // Modify middle element
692            let mut_ref = list.get_mut(1).unwrap();
693            *mut_ref *= 10; // 2 becomes 20
694
695            // Verify list structure is intact
696            assert_eq!(
697                list.len(),
698                3,
699                "list length should remain unchanged after get_mut()"
700            );
701            assert_eq!(list.head(), Some(&1), "head should remain the same");
702            assert_eq!(list.last(), Some(&3), "last should remain the same");
703
704            // Verify other elements are accessible and unchanged
705            assert_eq!(
706                *list.get(0).unwrap(),
707                1,
708                "first element should be unchanged"
709            );
710            assert_eq!(*list.get(2).unwrap(), 3, "last element should be unchanged");
711        }
712
713        #[test]
714        fn test_multiple_get_mut_calls() {
715            let mut list = SingleLinkedList::new();
716            list.push_back(10);
717            list.push_back(20);
718            list.push_back(30);
719
720            // First modification
721            let first = list.get_mut(0).unwrap();
722            *first += 5; // 10 becomes 15
723
724            // Second modification on different element
725            let last = list.get_mut(2).unwrap();
726            *last *= 2; // 30 becomes 60
727
728            // Final verification
729            let values: Vec<i32> = list.iter().copied().collect();
730            assert_eq!(
731                values,
732                vec![15, 20, 60],
733                "all modifications should be applied correctly"
734            );
735        }
736
737        #[test]
738        fn test_get_mut_then_get() {
739            let mut list = SingleLinkedList::new();
740            list.push_back(5);
741            list.push_back(15);
742            list.push_back(25);
743
744            // Modify using get_mut
745            let mid = list.get_mut(1).unwrap();
746            *mid = 99;
747
748            // Immediately read using get
749            let mid_value = list.get(1).unwrap();
750
751            assert_eq!(
752                *mid_value, 99,
753                "get() should reflect changes made by get_mut()"
754            );
755        }
756
757        #[test]
758        fn test_get_mut_error_propagation() {
759            let mut list = SingleLinkedList::new();
760            list.push_back(1);
761            list.push_back(2);
762
763            // Try to get mutable reference to out-of-bounds index
764            let result = list.get_mut(5);
765            assert!(
766                result.is_err(),
767                "get_mut() with out-of-bounds index should return error"
768            );
769
770            // Ensure list is still valid after failed operation
771            assert_eq!(
772                list.len(),
773                2,
774                "list should remain unchanged after failed get_mut()"
775            );
776            assert_eq!(*list.get(0).unwrap(), 1, "first element should remain 1");
777            assert_eq!(*list.get(1).unwrap(), 2, "second element should remain 2");
778        }
779    }
780
781    mod push {
782        use super::*;
783
784        #[test]
785        fn test_push_back() {
786            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
787            assert!(list.is_empty(), "is_empty() returns `false` after creation");
788
789            list.push_back(1);
790            assert_eq!(list.len(), 1, "bad length after push_back()");
791            assert_eq!(list.head(), Some(&1), "incorrect head after push_back()");
792            assert_eq!(list.last(), Some(&1), "incorrect last after push_back()");
793            assert!(
794                !list.is_empty(),
795                "is_empty() returns `true` after push_back()"
796            );
797
798            list.push_back(2);
799            assert_eq!(list.len(), 2, "bad length after push_back()");
800            assert!(list.head().is_some(), "head is None after push_back()");
801            assert_eq!(list.head(), Some(&1), "incorrect head payload");
802            assert_eq!(list.last(), Some(&2), "incorrect last after push_back()");
803            assert!(
804                !list.is_empty(),
805                "is_empty() returns `true` after push_back()"
806            );
807
808            let mut list: SingleLinkedList<String> = SingleLinkedList::new();
809            list.push_back("hello".to_string());
810            assert_eq!(list.len(), 1, "bad length after push_back()");
811            assert!(list.head().is_some(), "head is None after push_back()");
812            assert_eq!(list.head().unwrap(), "hello", "incorrect head payload");
813
814            let mut list: SingleLinkedList<&[char]> = SingleLinkedList::new();
815            list.push_back(&['a', 'b', 'c']);
816            assert_eq!(list.len(), 1, "bad length after push_back()");
817            assert!(list.head().is_some(), "head is None after push_back()");
818            assert_eq!(
819                list.head().unwrap(),
820                &['a', 'b', 'c'],
821                "incorrect head payload"
822            );
823        }
824
825        #[test]
826        fn test_push_to_empty_list_updates_head_and_last() {
827            let mut list = SingleLinkedList::new();
828
829            list.push_back(100);
830            assert_eq!(list.len(), 1);
831            assert_eq!(list.head(), Some(&100));
832            assert_eq!(list.last(), Some(&100));
833
834            let mut list2 = SingleLinkedList::new();
835            list2.push_front(200);
836            assert_eq!(list2.len(), 1);
837            assert_eq!(list2.head(), Some(&200));
838            assert_eq!(list2.last(), Some(&200));
839        }
840
841        #[test]
842        fn test_push_front() {
843            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
844            assert!(list.is_empty(), "is_empty() returns `false` after creation");
845
846            list.push_front(1);
847            assert_eq!(list.len(), 1, "bad length after push_front()");
848            assert_eq!(list.head(), Some(&1), "incorrect head after push_front()");
849            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
850            assert!(
851                !list.is_empty(),
852                "is_empty() returns `true` after push_front()"
853            );
854
855            list.push_front(2);
856            assert_eq!(list.len(), 2, "bad length after push_front()");
857            assert!(list.head().is_some(), "head is None after push_front()");
858            assert_eq!(list.head(), Some(&2), "incorrect head payload");
859            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
860            assert!(
861                !list.is_empty(),
862                "is_empty() returns `true` after push_front()"
863            );
864
865            let mut list: SingleLinkedList<String> = SingleLinkedList::new();
866            list.push_front("hello".to_string());
867            assert_eq!(list.len(), 1, "bad length after push_front()");
868            assert!(list.head().is_some(), "head is None after push_front()");
869            assert_eq!(list.head().unwrap(), "hello", "incorrect head payload");
870
871            let mut list: SingleLinkedList<&[char]> = SingleLinkedList::new();
872            list.push_front(&['a', 'b', 'c']);
873            assert_eq!(list.len(), 1, "bad length after push_front()");
874            assert!(list.head().is_some(), "head is None after push_front()");
875            assert_eq!(
876                list.head().unwrap(),
877                &['a', 'b', 'c'],
878                "incorrect head payload"
879            );
880        }
881
882        #[test]
883        fn test_mix_push() {
884            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
885            assert!(list.is_empty(), "is_empty() returns `false` after creation");
886
887            list.push_back(1);
888            assert_eq!(list.len(), 1, "bad length after push_back()");
889            assert_eq!(list.head(), Some(&1), "incorrect head after push_back()");
890            assert_eq!(list.last(), Some(&1), "incorrect last after push_back()");
891            assert!(
892                !list.is_empty(),
893                "is_empty() returns `true` after push_back()"
894            );
895
896            list.push_front(2);
897            assert_eq!(list.len(), 2, "bad length after push_front()");
898            assert!(list.head().is_some(), "head is None after push_front()");
899            assert_eq!(list.head(), Some(&2), "incorrect head payload");
900            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
901            assert!(
902                !list.is_empty(),
903                "is_empty() returns `true` after push_front()"
904            );
905
906            list.push_back(3);
907            assert_eq!(list.len(), 3, "bad length after push_back()");
908            assert!(list.head().is_some(), "head is None after push_back()");
909            assert_eq!(list.head(), Some(&2), "incorrect head payload");
910            assert_eq!(list.last(), Some(&3), "incorrect last after push_back()");
911            assert!(
912                !list.is_empty(),
913                "is_empty() returns `true` after push_back()"
914            );
915        }
916    }
917
918    mod pop {
919        use super::*;
920
921        #[test]
922        fn test_pop_back_empty_list() {
923            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
924            assert_eq!(
925                list.pop_back(),
926                None,
927                "pop_back from empty list should return None"
928            );
929            assert!(
930                list.is_empty(),
931                "list should remain empty after pop_back on empty"
932            );
933        }
934
935        #[test]
936        fn test_pop_back_single_element() {
937            let mut list = SingleLinkedList::new();
938            list.push_back(42);
939            assert_eq!(
940                list.pop_back(),
941                Some(42),
942                "pop_back() should return the only element"
943            );
944            assert!(
945                list.is_empty(),
946                "list should be empty after popping the last element"
947            );
948            assert_eq!(
949                list.head(),
950                None,
951                "head should be None after popping last element"
952            );
953            assert_eq!(
954                list.last(),
955                None,
956                "last should be None after popping last element"
957            );
958        }
959
960        #[test]
961        fn test_pop_back_multiple_elements() {
962            let mut list = setup_list(3); // [0, 1, 2]
963            assert_eq!(
964                list.pop_back(),
965                Some(2),
966                "pop_back() should return last element (2)"
967            );
968            assert_eq!(list.len(), 2, "size should decrease by 1 after pop_back()");
969            assert_eq!(list.last(), Some(&1), "new last element should be 1");
970
971            assert_eq!(list.pop_back(), Some(1), "pop_back() should return 1 next");
972            assert_eq!(list.len(), 1, "size should be 1 after second pop_back()");
973            assert_eq!(list.head(), Some(&0), "head should still be 0");
974            assert_eq!(list.last(), Some(&0), "last should now be 0");
975
976            assert_eq!(
977                list.pop_back(),
978                Some(0),
979                "pop_back() should return 0 finally"
980            );
981            assert!(list.is_empty(), "list should be empty after all pop-backs");
982        }
983
984        #[test]
985        fn test_pop_front_empty_list() {
986            let mut list = SingleLinkedList::<u8>::new();
987            assert_eq!(
988                list.pop_front(),
989                None,
990                "pop_front() from empty list should return None"
991            );
992            assert!(
993                list.is_empty(),
994                "list should remain empty after pop_front() on empty"
995            );
996        }
997
998        #[test]
999        fn test_pop_front_single_element() {
1000            let mut list = SingleLinkedList::new();
1001            list.push_front(99);
1002            assert_eq!(
1003                list.pop_front(),
1004                Some(99),
1005                "pop_front() should return the only element"
1006            );
1007            assert!(
1008                list.is_empty(),
1009                "list should be empty after popping the only element"
1010            );
1011            assert_eq!(list.head(), None, "head should be None after pop");
1012            assert_eq!(list.last(), None, "last should be None after pop");
1013        }
1014
1015        #[test]
1016        fn test_pop_front_multiple_elements() {
1017            let mut list = setup_list(3); // [0, 1, 2]
1018            assert_eq!(
1019                list.pop_front(),
1020                Some(0),
1021                "pop_front should return first element (0)"
1022            );
1023            assert_eq!(list.len(), 2, "size should decrease by 1 after pop_front");
1024            assert_eq!(list.head(), Some(&1), "new head should be 1");
1025            assert_eq!(list.last(), Some(&2), "last should remain 2");
1026
1027            assert_eq!(list.pop_front(), Some(1), "pop_front should return 1 next");
1028            assert_eq!(list.len(), 1, "size should be 1 after second pop_front");
1029            assert_eq!(list.head(), Some(&2), "head should now be 2");
1030            assert_eq!(list.last(), Some(&2), "last should also be 2");
1031
1032            assert_eq!(
1033                list.pop_front(),
1034                Some(2),
1035                "pop_front should return 2 finally"
1036            );
1037            assert!(list.is_empty(), "list should be empty after all pop_fronts");
1038        }
1039    }
1040
1041    mod mixed {
1042        use super::*;
1043
1044        #[test]
1045        fn test_mixed_push_pop_operations() {
1046            let mut list = SingleLinkedList::new();
1047
1048            list.push_back(1);
1049            list.push_front(0);
1050            list.push_back(2);
1051
1052            // List: [0, 1, 2]
1053            assert_eq!(list.len(), 3);
1054            assert_eq!(list.head(), Some(&0));
1055            assert_eq!(list.last(), Some(&2));
1056
1057            assert_eq!(list.pop_front(), Some(0));
1058            assert_eq!(list.pop_back(), Some(2));
1059            assert_eq!(list.pop_front(), Some(1));
1060            assert!(list.is_empty());
1061
1062            // Try one more pop
1063            assert_eq!(list.pop_back(), None);
1064            assert_eq!(list.pop_front(), None);
1065        }
1066
1067        #[test]
1068        fn test_size_consistency_after_operations() {
1069            let mut list = SingleLinkedList::new();
1070
1071            // Push back
1072            list.push_back(10);
1073            assert_eq!(list.len(), 1, "size after push_back(10) should be 1");
1074
1075            list.push_back(20);
1076            assert_eq!(list.len(), 2, "size after second push_back should be 2");
1077
1078            // Pop back
1079            list.pop_back();
1080            assert_eq!(list.len(), 1, "size after pop_back should be 1");
1081
1082            // Push front
1083            list.push_front(5);
1084            assert_eq!(list.len(), 2, "size after push_front(5) should be 2");
1085
1086            // Pop front
1087            list.pop_front();
1088            assert_eq!(list.len(), 1, "size after pop_front should be 1");
1089
1090            // Final pop
1091            list.pop_back();
1092            assert_eq!(list.len(), 0, "size should be 0 after all pops");
1093            assert!(list.is_empty(), "list should be empty");
1094        }
1095
1096        #[test]
1097        fn test_head_last_consistency_after_mixed_operations() {
1098            let mut list = SingleLinkedList::new();
1099
1100            // Start: empty
1101            assert_eq!(list.head(), None);
1102            assert_eq!(list.last(), None);
1103
1104            // push_back(1)
1105            list.push_back(1);
1106            assert_eq!(list.head(), Some(&1));
1107            assert_eq!(list.last(), Some(&1));
1108
1109            // push_front(0)
1110            list.push_front(0);
1111            assert_eq!(list.head(), Some(&0));
1112            assert_eq!(list.last(), Some(&1));
1113
1114            // push_back(2)
1115            list.push_back(2);
1116            assert_eq!(list.head(), Some(&0));
1117            assert_eq!(list.last(), Some(&2));
1118
1119            // pop_front() → removes 0
1120            list.pop_front();
1121            assert_eq!(list.head(), Some(&1));
1122            assert_eq!(list.last(), Some(&2));
1123
1124            // pop_back() → removes 2
1125            list.pop_back();
1126            assert_eq!(list.head(), Some(&1));
1127            assert_eq!(list.last(), Some(&1));
1128
1129            // Final pop
1130            list.pop_front();
1131            assert_eq!(list.head(), None);
1132            assert_eq!(list.last(), None);
1133            assert!(list.is_empty());
1134        }
1135    }
1136
1137    mod complex_types {
1138        use super::*;
1139
1140        #[test]
1141        fn test_complex_types_string() {
1142            let mut list = SingleLinkedList::new();
1143            list.push_back("hello".to_string());
1144            list.push_back("world".to_string());
1145
1146            assert_eq!(list.len(), 2);
1147            assert_eq!(list.head().unwrap(), "hello");
1148            assert_eq!(list.last().unwrap(), "world");
1149
1150            assert_eq!(list.pop_front().unwrap(), "hello".to_string());
1151            assert_eq!(list.pop_back().unwrap(), "world".to_string());
1152            assert!(list.is_empty());
1153        }
1154
1155        #[test]
1156        fn test_complex_types_vec() {
1157            let mut list = SingleLinkedList::new();
1158            list.push_back(vec![1, 2]);
1159            list.push_back(vec![3, 4]);
1160
1161            assert_eq!(list.len(), 2);
1162            assert_eq!(list.head().unwrap(), &vec![1, 2]);
1163            assert_eq!(list.last().unwrap(), &vec![3, 4]);
1164
1165            let popped_front = list.pop_front().unwrap();
1166            assert_eq!(popped_front, vec![1, 2]);
1167
1168            let popped_back = list.pop_back().unwrap();
1169            assert_eq!(popped_back, vec![3, 4]);
1170            assert!(list.is_empty());
1171        }
1172    }
1173
1174    mod insert {
1175        use super::*;
1176
1177        #[test]
1178        fn test_insert_at_beginning_empty_list() {
1179            let mut list = SingleLinkedList::new();
1180            assert!(
1181                list.insert(0, 42).is_ok(),
1182                "insert at index 0 in empty list should succeed"
1183            );
1184            assert_eq!(list.len(), 1, "list size should be 1 after insertion");
1185            assert_eq!(list.head(), Some(&42), "head should contain inserted value");
1186            assert_eq!(list.last(), Some(&42), "last should contain inserted value");
1187        }
1188
1189        #[test]
1190        fn test_insert_at_beginning_non_empty_list() {
1191            let mut list = setup_list(3); // [0, 1, 2]
1192            assert!(
1193                list.insert(0, 99).is_ok(),
1194                "insert at beginning should succeed"
1195            );
1196            assert_eq!(list.len(), 4, "size should increase by 1");
1197            assert_eq!(list.head(), Some(&99), "new head should be 99");
1198            assert_eq!(list.find(&99), Some(0), "find should locate 99 at index 0");
1199        }
1200
1201        #[test]
1202        fn test_insert_at_end() {
1203            let mut list = setup_list(2); // [0, 1]
1204            assert!(
1205                list.insert(2, 999).is_ok(),
1206                "insert at end (index == size) should succeed"
1207            );
1208            assert_eq!(list.len(), 3, "size should increase by 1");
1209            assert_eq!(list.last(), Some(&999), "last element should be 999");
1210            assert_eq!(
1211                list.find(&999),
1212                Some(2),
1213                "find should locate 999 at index 2"
1214            );
1215        }
1216
1217        #[test]
1218        fn test_insert_in_middle() {
1219            let mut list = setup_list(3); // [0, 1, 2]
1220            assert!(
1221                list.insert(1, 50).is_ok(),
1222                "insert in middle should succeed"
1223            );
1224            assert_eq!(list.len(), 4, "size should increase by 1");
1225
1226            // Verify the order: [0, 50, 1, 2]
1227            let mut iter = list.iter();
1228            assert_eq!(iter.next(), Some(&0));
1229            assert_eq!(iter.next(), Some(&50));
1230            assert_eq!(iter.next(), Some(&1));
1231            assert_eq!(iter.next(), Some(&2));
1232        }
1233
1234        #[test]
1235        fn test_insert_out_of_bounds() {
1236            let mut list = setup_list(2); // [0, 1]
1237
1238            // Index greater than size
1239            assert!(
1240                list.insert(3, 42).is_err(),
1241                "insert with index > size should return error"
1242            );
1243
1244            // Very large index
1245            assert!(
1246                list.insert(100, 42).is_err(),
1247                "insert with large out-of-bounds index should return error"
1248            );
1249
1250            // Empty list with non-zero index
1251            let mut empty_list = SingleLinkedList::new();
1252            assert!(
1253                empty_list.insert(1, 42).is_err(),
1254                "insert to empty list with index > 0 should return error"
1255            );
1256        }
1257
1258        #[test]
1259        fn test_insert_with_complex_types_string() {
1260            let mut list = SingleLinkedList::new();
1261            list.push_back("first".to_string());
1262            list.push_back("third".to_string());
1263
1264            assert!(
1265                list.insert(1, "second".to_string()).is_ok(),
1266                "insert string in middle should succeed"
1267            );
1268            assert_eq!(list.len(), 3, "size should be 3 after insertion");
1269
1270            // Verify order: ["first", "second", "third"]
1271            let values: Vec<String> = list.iter().map(|payload| payload.clone()).collect();
1272            assert_eq!(values, vec!["first", "second", "third"]);
1273        }
1274
1275        #[test]
1276        fn test_insert_multiple_times() {
1277            let mut list = SingleLinkedList::new();
1278
1279            // Insert at various positions multiple times
1280            assert!(list.insert(0, 10).is_ok());
1281            assert!(list.insert(1, 30).is_ok());
1282            assert!(list.insert(1, 20).is_ok()); // Insert between 10 and 30
1283
1284            assert_eq!(list.len(), 3, "final size should be 3");
1285
1286            // Expected order: [10, 20, 30]
1287            let mut iter = list.iter();
1288            assert_eq!(iter.next(), Some(&10));
1289            assert_eq!(iter.next(), Some(&20));
1290            assert_eq!(iter.next(), Some(&30));
1291        }
1292
1293        #[test]
1294        fn test_insert_preserves_head_and_last_pointers() {
1295            let mut list = setup_list(2); // [0, 1]
1296
1297            // Insert in the middle
1298            assert!(list.insert(1, 5).is_ok());
1299
1300            // Head should still be the first element
1301            assert_eq!(list.head(), Some(&0), "head pointer should remain correct");
1302
1303            // Last should still be the last element
1304            assert_eq!(list.last(), Some(&1), "last pointer should remain correct");
1305        }
1306
1307        #[test]
1308        fn test_insert_edge_cases() {
1309            // Test inserting into a list with one element
1310            let mut single_element = SingleLinkedList::new();
1311            single_element.push_back(100);
1312
1313            // Insert at beginning (should work)
1314            assert!(single_element.insert(0, 50).is_ok());
1315            assert_eq!(single_element.find(&50), Some(0));
1316            assert_eq!(single_element.find(&100), Some(1));
1317
1318            // Insert at end (should work)
1319            assert!(single_element.insert(2, 150).is_ok());
1320            assert_eq!(single_element.find(&150), Some(2));
1321        }
1322    }
1323
1324    mod remove {
1325        use super::*;
1326
1327        #[test]
1328        fn test_remove_from_empty_list() {
1329            let mut list = SingleLinkedList::<u8>::new();
1330            assert!(
1331                list.remove(0).is_err(),
1332                "remove from empty list should return error"
1333            );
1334            assert_eq!(list.len(), 0, "size should remain 0");
1335        }
1336
1337        #[test]
1338        fn test_remove_first_element() {
1339            let mut list = setup_list(3); // [0, 1, 2]
1340            let removed = list.remove(0).unwrap();
1341            assert_eq!(removed, 0, "removed value should be 0 (first element)");
1342            assert_eq!(list.len(), 2, "size should decrease by 1");
1343            assert_eq!(list.head(), Some(&1), "new head should be 1");
1344            assert_eq!(list.find(&0), None, "0 should no longer be in the list");
1345        }
1346
1347        #[test]
1348        fn test_remove_last_element() {
1349            let mut list = setup_list(3); // [0, 1, 2]
1350            let removed = list.remove(2).unwrap(); // index = size - 1
1351            assert_eq!(removed, 2, "removed value should be 2 (last element)");
1352            assert_eq!(list.len(), 2, "size should decrease by 1");
1353            assert_eq!(list.last(), Some(&1), "new last should be 1");
1354            assert_eq!(list.find(&2), None, "2 should no longer be in the list");
1355        }
1356
1357        #[test]
1358        fn test_remove_middle_element() {
1359            let mut list = setup_list(4); // [0, 1, 2, 3]
1360            let removed = list.remove(1).unwrap(); // remove element at index 1 (value 1)
1361            assert_eq!(removed, 1, "removed value should be 1");
1362            assert_eq!(list.len(), 3, "size should decrease by 1");
1363
1364            // Verify the order: [0, 2, 3]
1365            let values: Vec<usize> = list.iter().copied().collect();
1366            assert_eq!(
1367                values,
1368                vec![0, 2, 3],
1369                "list should have correct order after removal"
1370            );
1371        }
1372
1373        #[test]
1374        fn test_remove_out_of_bounds() {
1375            let mut list = setup_list(2); // [0, 1]
1376
1377            // Index equal to size (should be out of bounds)
1378            assert!(
1379                list.remove(2).is_err(),
1380                "remove with index == size should return error"
1381            );
1382
1383            // Index greater than size
1384            assert!(
1385                list.remove(5).is_err(),
1386                "remove with large out-of-bounds index should return error"
1387            );
1388
1389            // Empty list
1390            let mut empty_list = SingleLinkedList::<u8>::new();
1391            assert!(
1392                empty_list.remove(0).is_err(),
1393                "remove from empty list should return error"
1394            );
1395        }
1396
1397        #[test]
1398        fn test_remove_single_element_list() {
1399            let mut list = SingleLinkedList::new();
1400            list.push_back(42);
1401            let removed = list.remove(0).unwrap();
1402            assert_eq!(removed, 42, "removed value should be 42");
1403            assert!(
1404                list.is_empty(),
1405                "list should be empty after removing the only element"
1406            );
1407            assert_eq!(list.head(), None, "head should be None");
1408            assert_eq!(list.last(), None, "last should be None");
1409        }
1410
1411        #[test]
1412        fn test_remove_preserves_head_and_last_pointers() {
1413            let mut list = setup_list(4); // [0, 1, 2, 3]
1414
1415            // Remove middle element (index 1, value 1)
1416            let _ = list.remove(1);
1417
1418            assert_eq!(list.head(), Some(&0), "head pointer should remain correct");
1419            assert_eq!(list.last(), Some(&3), "last pointer should remain correct");
1420        }
1421
1422        #[test]
1423        fn test_multiple_removes() {
1424            let mut list = setup_list(5); // [0, 1, 2, 3, 4]
1425
1426            // Remove second element (index 1, value 1)
1427            let removed1 = list.remove(1).unwrap();
1428            assert_eq!(removed1, 1);
1429            assert_eq!(list.len(), 4);
1430
1431            // Remove new second element (was 2, now at index 1)
1432            let removed2 = list.remove(1).unwrap();
1433            assert_eq!(removed2, 2);
1434            assert_eq!(list.len(), 3);
1435
1436            // Final state should be [0, 3, 4]
1437            let final_values: Vec<usize> = list.iter().copied().collect();
1438            assert_eq!(
1439                final_values,
1440                vec![0, 3, 4],
1441                "list should have correct values after multiple removes"
1442            );
1443        }
1444
1445        #[test]
1446        fn test_remove_with_complex_types_string() {
1447            let mut list = SingleLinkedList::new();
1448            list.push_back("first".to_string());
1449            list.push_back("second".to_string());
1450            list.push_back("third".to_string());
1451
1452            let removed = list.remove(1).unwrap(); // Remove "second"
1453            assert_eq!(
1454                removed,
1455                "second".to_string(),
1456                "removed value should be 'second'"
1457            );
1458            assert_eq!(list.len(), 2, "size should be 2 after removal");
1459
1460            // Verify order: ["first", "third"]
1461            let remaining: Vec<String> = list.iter().map(|s| s.clone()).collect();
1462            assert_eq!(remaining, vec!["first", "third"]);
1463        }
1464
1465        #[test]
1466        fn test_remove_edge_cases() {
1467            // Test removing from a list with two elements
1468            let mut two_elements = SingleLinkedList::new();
1469            two_elements.push_back(10);
1470            two_elements.push_back(20);
1471
1472            // Remove first (index 0)
1473            let removed_first = two_elements.remove(0).unwrap();
1474            assert_eq!(removed_first, 10);
1475            assert_eq!(two_elements.len(), 1);
1476            assert_eq!(two_elements.head(), Some(&20));
1477
1478            // Now remove the last (only remaining) element
1479            let removed_last = two_elements.remove(0).unwrap();
1480            assert_eq!(removed_last, 20);
1481            assert!(two_elements.is_empty());
1482        }
1483    }
1484
1485    mod clear {
1486        use super::*;
1487
1488        #[test]
1489        fn test_clear_empty_list() {
1490            let mut list = SingleLinkedList::<u8>::new();
1491            assert!(list.is_empty(), "list should be empty initially");
1492
1493            list.clear();
1494
1495            assert!(
1496                list.is_empty(),
1497                "clear() on empty list should leave it empty"
1498            );
1499            assert_eq!(
1500                list.len(),
1501                0,
1502                "length should remain 0 after clear() on empty list"
1503            );
1504            assert_eq!(
1505                list.head(),
1506                None,
1507                "head should be None after clear() on empty list"
1508            );
1509            assert_eq!(
1510                list.last(),
1511                None,
1512                "last should be None after clear() on empty list"
1513            );
1514        }
1515
1516        #[test]
1517        fn test_clear_single_element_list() {
1518            let mut list = SingleLinkedList::new();
1519            list.push_back(42);
1520            assert!(!list.is_empty(), "list should not be empty before clear()");
1521            assert_eq!(list.len(), 1, "list should have length 1 before clear()");
1522
1523            list.clear();
1524
1525            assert!(list.is_empty(), "list should be empty after clear()");
1526            assert_eq!(list.len(), 0, "length should be 0 after clear()");
1527            assert_eq!(list.head(), None, "head should be None after clear()");
1528            assert_eq!(list.last(), None, "last should be None after clear()");
1529        }
1530
1531        #[test]
1532        fn test_clear_multiple_elements_list() {
1533            let mut list = SingleLinkedList::new();
1534            list.push_back(10);
1535            list.push_back(20);
1536            list.push_back(30);
1537            assert_eq!(list.len(), 3, "list should have 3 elements before clear()");
1538
1539            list.clear();
1540
1541            assert!(
1542                list.is_empty(),
1543                "list should be empty after clearing multiple elements"
1544            );
1545            assert_eq!(
1546                list.len(),
1547                0,
1548                "length should be 0 after clearing multiple elements"
1549            );
1550            assert_eq!(
1551                list.head(),
1552                None,
1553                "head should be None after clearing multiple elements"
1554            );
1555            assert_eq!(
1556                list.last(),
1557                None,
1558                "last should be None after clearing multiple elements"
1559            );
1560        }
1561
1562        #[test]
1563        fn test_clear_then_reuse_list() {
1564            let mut list = SingleLinkedList::new();
1565            list.push_back(1);
1566            list.push_back(2);
1567
1568            list.clear();
1569            assert!(list.is_empty(), "list should be empty after clear()");
1570
1571            // Reuse the list after clearing
1572            list.push_back(100);
1573            list.push_back(200);
1574
1575            assert_eq!(
1576                list.len(),
1577                2,
1578                "list should accept new elements after clear()"
1579            );
1580            assert_eq!(*list.head().unwrap(), 100, "new head should be 100");
1581            assert_eq!(*list.last().unwrap(), 200, "new last should be 200");
1582        }
1583
1584        #[test]
1585        fn test_clear_with_complex_types() {
1586            // Test with String
1587            let mut string_list = SingleLinkedList::new();
1588            string_list.push_back("apple".to_string());
1589            string_list.push_back("banana".to_string());
1590
1591            string_list.clear();
1592            assert!(
1593                string_list.is_empty(),
1594                "string list should be empty after clear()"
1595            );
1596            assert_eq!(
1597                string_list.len(),
1598                0,
1599                "string list length should be 0 after clear()"
1600            );
1601
1602            // Test with Vec
1603            let mut vec_list = SingleLinkedList::new();
1604            vec_list.push_back(vec![1, 2]);
1605            vec_list.push_back(vec![3, 4]);
1606
1607            vec_list.clear();
1608            assert!(
1609                vec_list.is_empty(),
1610                "vec list should be empty after clear()"
1611            );
1612            assert_eq!(
1613                vec_list.len(),
1614                0,
1615                "vec list length should be 0 after clear()"
1616            );
1617        }
1618
1619        #[test]
1620        fn test_clear_preserves_list_integrity() {
1621            let mut list = SingleLinkedList::new();
1622            list.push_back(5);
1623            list.push_back(10);
1624            list.push_back(15);
1625
1626            let initial_len = list.len();
1627            let head_before = list.head().cloned();
1628            let last_before = list.last().cloned();
1629            assert_eq!(initial_len, 3);
1630            assert_eq!(head_before.unwrap(), 5);
1631            assert_eq!(last_before.unwrap(), 15);
1632
1633            list.clear();
1634
1635            // Verify the list is properly cleared
1636            assert!(list.is_empty(), "list should be empty after clear()");
1637            assert_eq!(list.len(), 0, "length should be 0 after clear()");
1638            assert_eq!(list.head(), None, "head should be None after clear()");
1639            assert_eq!(list.last(), None, "last should be None after clear()");
1640
1641            // Ensure we can create a new list and it works correctly
1642            let mut new_list = SingleLinkedList::new();
1643            new_list.push_back(100);
1644            assert_eq!(
1645                new_list.len(),
1646                1,
1647                "new list should work correctly after previous clear()"
1648            );
1649        }
1650
1651        #[test]
1652        fn test_clear_performance_consistency() {
1653            // Test that clear() works correctly regardless of list size
1654            for size in &[0, 1, 5, 10, 100] {
1655                let mut list = SingleLinkedList::new();
1656
1657                // Fill list with values
1658                for i in 0..*size {
1659                    list.push_back(i);
1660                }
1661
1662                assert_eq!(
1663                    list.len(),
1664                    *size,
1665                    "list should have correct length before clear() for size {}",
1666                    size
1667                );
1668
1669                list.clear();
1670
1671                assert!(
1672                    list.is_empty(),
1673                    "list of size {} should be empty after clear()",
1674                    size
1675                );
1676                assert_eq!(
1677                    list.len(),
1678                    0,
1679                    "list of size {} should have length 0 after clear()",
1680                    size
1681                );
1682                assert_eq!(
1683                    list.head(),
1684                    None,
1685                    "head should be None for cleared list of size {}",
1686                    size
1687                );
1688                assert_eq!(
1689                    list.last(),
1690                    None,
1691                    "last should be None for cleared list of size {}",
1692                    size
1693                );
1694            }
1695        }
1696
1697        #[test]
1698        fn test_clear_after_mixed_operations() {
1699            let mut list = SingleLinkedList::new();
1700
1701            // Perform various operations
1702            list.push_back(1);
1703            list.push_front(0);
1704            list.push_back(2);
1705            list.pop_front(); // removes 0
1706            list.push_back(3);
1707
1708            // List should now be [1, 2, 3]
1709            assert_eq!(
1710                list.len(),
1711                3,
1712                "list should have 3 elements after mixed operations"
1713            );
1714            assert_eq!(
1715                *list.head().unwrap(),
1716                1,
1717                "head should be 1 after mixed operations"
1718            );
1719            assert_eq!(
1720                *list.last().unwrap(),
1721                3,
1722                "last should be 3 after mixed operations"
1723            );
1724
1725            list.clear();
1726
1727            assert!(
1728                list.is_empty(),
1729                "list should be empty after clear() following mixed operations"
1730            );
1731            assert_eq!(
1732                list.len(),
1733                0,
1734                "length should be 0 after clear() following mixed operations"
1735            );
1736            assert_eq!(
1737                list.head(),
1738                None,
1739                "head should be None after clear() following mixed operations"
1740            );
1741            assert_eq!(
1742                list.last(),
1743                None,
1744                "last should be None after clear() following mixed operations"
1745            );
1746        }
1747    }
1748
1749    mod sort {
1750        use super::*;
1751
1752        /// Helper function to collect list values into a vector for easy comparison
1753        fn list_to_vec(list: &SingleLinkedList<i32>) -> Vec<i32> {
1754            let mut result = Vec::new();
1755            let mut current = list.head;
1756            while !current.is_null() {
1757                unsafe {
1758                    result.push((*current).payload);
1759                    current = (*current).next;
1760                }
1761            }
1762            result
1763        }
1764
1765        #[test]
1766        fn test_sort_empty_list() {
1767            let mut list = SingleLinkedList::<i32>::new();
1768            assert_eq!(list.len(), 0, "list should be empty initially");
1769
1770            list.sort();
1771
1772            assert_eq!(list.len(), 0, "empty list should remain empty after sort()");
1773            assert!(list.is_empty(), "empty list should be empty after sort()");
1774        }
1775
1776        #[test]
1777        fn test_sort_single_element() {
1778            let mut list = SingleLinkedList::new();
1779            list.push_back(42);
1780            assert_eq!(list.len(), 1, "list should have one element");
1781
1782            list.sort();
1783
1784            assert_eq!(list.len(), 1, "single element list should have same length after sort()");
1785            let values = list_to_vec(&list);
1786            assert_eq!(values, vec![42], "single element should remain unchanged");
1787        }
1788
1789        #[test]
1790        fn test_sort_already_sorted() {
1791            let mut list = SingleLinkedList::from_slice(&[1, 2, 3, 4, 5]);
1792            assert_eq!(list.len(), 5, "list should have 5 elements");
1793
1794            list.sort();
1795
1796            let values = list_to_vec(&list);
1797            assert_eq!(values, vec![1, 2, 3, 4, 5], "already sorted list should remain sorted");
1798        }
1799
1800        #[test]
1801        fn test_sort_reverse_sorted() {
1802            let mut list = SingleLinkedList::from_slice(&[5, 4, 3, 2, 1]);
1803            assert_eq!(list.len(), 5, "list should have 5 elements");
1804
1805            list.sort();
1806
1807            let values = list_to_vec(&list);
1808            assert_eq!(values, vec![1, 2, 3, 4, 5], "reverse sorted list should become ascending");
1809        }
1810
1811        #[test]
1812        fn test_sort_random_order() {
1813            let mut list = SingleLinkedList::from_slice(&[3, 1, 4, 1, 5, 9, 2, 6]);
1814            assert_eq!(list.len(), 8, "list should have 8 elements");
1815
1816            list.sort();
1817
1818            let values = list_to_vec(&list);
1819            assert_eq!(values, vec![1, 1, 2, 3, 4, 5, 6, 9], "random order list should be sorted correctly");
1820        }
1821
1822        #[test]
1823        fn test_sort_with_duplicates() {
1824            let mut list = SingleLinkedList::from_slice(&[2, 2, 1, 1, 3, 3]);
1825            assert_eq!(list.len(), 6, "list should have 6 elements");
1826
1827            list.sort();
1828
1829            let values = list_to_vec(&list);
1830            assert_eq!(values, vec![1, 1, 2, 2, 3, 3], "list with duplicates should be sorted with duplicates preserved");
1831        }
1832
1833        #[test]
1834        fn test_sort_two_elements_unsorted() {
1835            let mut list = SingleLinkedList::from_slice(&[2, 1]);
1836            assert_eq!(list.len(), 2, "list should have 2 elements");
1837
1838            list.sort();
1839
1840            let values = list_to_vec(&list);
1841            assert_eq!(values, vec![1, 2], "two elements should be sorted in ascending order");
1842        }
1843
1844        #[test]
1845        fn test_sort_two_elements_sorted() {
1846            let mut list = SingleLinkedList::from_slice(&[1, 2]);
1847            assert_eq!(list.len(), 2, "list should have 2 elements");
1848
1849            list.sort();
1850
1851            let values = list_to_vec(&list);
1852            assert_eq!(values, vec![1, 2], "already sorted two elements should remain the same");
1853        }
1854
1855        #[test]
1856        fn test_sort_large_list() {
1857            // Create a large list with random-like pattern
1858            let mut data: Vec<i32> = (1..=1000).collect();
1859            // Shuffle by reversing every 10 elements
1860            for chunk in data.chunks_mut(10) {
1861                chunk.reverse();
1862            }
1863
1864            let mut list = SingleLinkedList::new();
1865            for &value in &data {
1866                list.push_back(value);
1867            }
1868
1869            assert_eq!(list.len(), 1000, "large list should have 1000 elements");
1870
1871            list.sort();
1872
1873            let sorted_data: Vec<i32> = (1..=1000).collect();
1874            let values = list_to_vec(&list);
1875            assert_eq!(values, sorted_data, "large list should be sorted correctly");
1876        }
1877
1878        #[test]
1879        fn test_sort_after_operations() {
1880            let mut list = SingleLinkedList::new();
1881
1882            // Perform various operations
1883            list.push_back(5);
1884            list.push_front(1);
1885            list.push_back(3);
1886            list.pop_front(); // removes 1
1887            list.push_back(2);
1888
1889            // List should now be [5, 3, 2]
1890            assert_eq!(list.len(), 3, "list should have 3 elements after mixed operations");
1891
1892            list.sort();
1893
1894            let values = list_to_vec(&list);
1895            assert_eq!(values, vec![2, 3, 5], "list after mixed operations should be sorted correctly");
1896        }
1897
1898        #[test]
1899        fn test_sort_string_list() {
1900            let mut list = SingleLinkedList::new();
1901            list.push_back("zebra".to_string());
1902            list.push_back("apple".to_string());
1903            list.push_back("banana".to_string());
1904            list.push_back("cherry".to_string());
1905
1906            assert_eq!(list.len(), 4, "string list should have 4 elements");
1907
1908            list.sort();
1909
1910            let values: Vec<String> = list.into_iter().collect();
1911
1912            assert_eq!(
1913                values,
1914                vec!["apple".to_string(), "banana".to_string(), "cherry".to_string(), "zebra".to_string()],
1915                "string list should be sorted alphabetically"
1916            );
1917        }
1918
1919        #[test]
1920        fn test_sort_preserves_last_pointer() {
1921            let mut list = SingleLinkedList::from_slice(&[3, 1, 4, 2]);
1922
1923            list.sort();
1924
1925            // Verify that last pointer is correctly set to the last node
1926            let last_value = unsafe { (*list.last).payload };
1927            assert_eq!(last_value, 4, "last pointer should point to the maximum element after sorting");
1928        }
1929    }
1930
1931    mod memory_leaks {
1932        use super::*;
1933        use drop_tracker::DropTracker;
1934
1935        #[test]
1936        fn test_memory_leaks() {
1937            let mut tracker = DropTracker::new();
1938
1939            let mut list = SingleLinkedList::new();
1940            for i in 0..100 {
1941                list.push_back(tracker.track(i));
1942            }
1943            for i in 100..111 {
1944                list.push_front(tracker.track(i));
1945            }
1946
1947            assert_eq!(tracker.alive().count(), 111);
1948
1949            drop(list);
1950
1951            assert_eq!(tracker.alive().count(), 0);
1952            assert_eq!(tracker.dropped().count(), 111);
1953        }
1954
1955        #[test]
1956        fn test_iterators_with_drop_tracker() {
1957            let mut tracker = DropTracker::new();
1958
1959            let mut list = SingleLinkedList::new();
1960            for i in 0..5 {
1961                list.push_back(tracker.track(i));
1962            }
1963
1964            assert_eq!(tracker.alive().count(), 5);
1965
1966            // Используем все типы итераторов последовательно
1967            {
1968                // Итератор по ссылкам
1969                let ref_count: usize = list.iter().count();
1970                assert_eq!(ref_count, 5);
1971            }
1972
1973            {
1974                // Изменяемый итератор (изменяем все элементы)
1975                for item in list.iter_mut() {
1976                    **item += 10;
1977                }
1978            }
1979
1980            {
1981                // IntoIterator — забираем владение
1982                let collected: Vec<_> = list.into_iter().collect();
1983                assert_eq!(collected, vec![10, 11, 12, 13, 14]);
1984            }
1985
1986            // После IntoIterator список уничтожен
1987            assert_eq!(tracker.alive().count(), 0);
1988            assert_eq!(tracker.dropped().count(), 5);
1989        }
1990
1991        #[test]
1992        fn test_memory_leaks_with_remove_operations() {
1993            let mut tracker = DropTracker::new();
1994
1995            let mut list = SingleLinkedList::new();
1996            for i in 0..50 {
1997                list.push_back(tracker.track(i));
1998            }
1999
2000            assert_eq!(
2001                tracker.alive().count(),
2002                50,
2003                "50 elements should be alive after push_back"
2004            );
2005
2006            // Удаляем элементы с разных позиций
2007            assert_eq!(list.remove(0).unwrap(), 0);
2008            assert_eq!(list.remove(48).unwrap(), 49); // последний элемент
2009            assert_eq!(list.remove(24).unwrap(), 25); // средний элемент
2010
2011            assert_eq!(
2012                tracker.alive().count(),
2013                47,
2014                "After removing 3 elements, 47 should remain alive"
2015            );
2016
2017            // Полностью очищаем список
2018            while list.len() > 0 {
2019                let _ = list.pop_front();
2020            }
2021
2022            assert_eq!(
2023                tracker.alive().count(),
2024                0,
2025                "All elements should be dropped after clearing the list"
2026            );
2027            assert_eq!(
2028                tracker.dropped().count(),
2029                50,
2030                "All 50 elements should have been dropped"
2031            );
2032        }
2033
2034        #[test]
2035        fn test_memory_leaks_with_insert_operations() {
2036            let mut tracker = DropTracker::new();
2037
2038            let mut list = SingleLinkedList::new();
2039            list.push_back(tracker.track(1));
2040            list.push_back(tracker.track(3));
2041
2042            assert_eq!(
2043                tracker.alive().count(),
2044                2,
2045                "2 elements should be alive initially"
2046            );
2047
2048            // Вставляем элемент в середину
2049            list.insert(1, tracker.track(2)).unwrap();
2050
2051            assert_eq!(
2052                tracker.alive().count(),
2053                3,
2054                "3 elements should be alive after insert"
2055            );
2056
2057            // Вставляем в начало и конец
2058            list.insert(0, tracker.track(0)).unwrap();
2059            list.insert(3, tracker.track(4)).unwrap();
2060
2061            assert_eq!(
2062                tracker.alive().count(),
2063                5,
2064                "5 elements should be alive after all inserts"
2065            );
2066
2067            drop(list);
2068
2069            assert_eq!(
2070                tracker.alive().count(),
2071                0,
2072                "All elements should be dropped when list is dropped"
2073            );
2074            assert_eq!(
2075                tracker.dropped().count(),
2076                5,
2077                "All 5 elements should have been dropped"
2078            );
2079        }
2080
2081        #[test]
2082        fn test_memory_leaks_partial_operations() {
2083            let mut tracker = DropTracker::new();
2084
2085            let mut list = SingleLinkedList::new();
2086            for i in 0..20 {
2087                list.push_back(tracker.track(i));
2088            }
2089
2090            assert_eq!(tracker.alive().count(), 20, "20 elements should be alive");
2091
2092            // Выполняем несколько операций удаления и добавления
2093            for _ in 0..5 {
2094                let _ = list.pop_back();
2095            }
2096            for i in 100..103 {
2097                list.push_front(tracker.track(i));
2098            }
2099
2100            assert!(
2101                tracker.alive().count() < 20,
2102                "Fewer elements should be alive after partial operations"
2103            );
2104
2105            drop(list);
2106
2107            assert_eq!(
2108                tracker.alive().count(),
2109                0,
2110                "All remaining elements should be dropped"
2111            );
2112            assert_eq!(
2113                tracker.dropped().count(),
2114                23,
2115                "Total 23 elements should have been dropped (20 original + 3 added - 5 removed)"
2116            );
2117        }
2118
2119        #[test]
2120        fn test_memory_leaks_with_complex_types() {
2121            let mut tracker = DropTracker::new();
2122
2123            #[derive(Debug, PartialEq, Eq, Hash, Clone)]
2124            struct ComplexStruct {
2125                id: usize,
2126                data: String,
2127            }
2128
2129            impl Drop for ComplexStruct {
2130                fn drop(&mut self) {
2131                    // Просто отмечаем удаление
2132                }
2133            }
2134
2135            let mut list = SingleLinkedList::new();
2136            for i in 0..15 {
2137                list.push_back(tracker.track(ComplexStruct {
2138                    id: i,
2139                    data: format!("data_{}", i),
2140                }));
2141            }
2142
2143            assert_eq!(
2144                tracker.alive().count(),
2145                15,
2146                "15 ComplexStruct elements should be alive"
2147            );
2148
2149            // Удаляем несколько элементов
2150            for _ in 0..3 {
2151                let _ = list.pop_front();
2152            }
2153
2154            assert_eq!(
2155                tracker.alive().count(),
2156                12,
2157                "12 ComplexStruct elements should remain alive"
2158            );
2159
2160            drop(list);
2161
2162            assert_eq!(
2163                tracker.alive().count(),
2164                0,
2165                "All ComplexStruct elements should be dropped"
2166            );
2167            assert_eq!(
2168                tracker.dropped().count(),
2169                15,
2170                "All 15 ComplexStruct elements should have been dropped"
2171            );
2172        }
2173
2174        #[test]
2175        fn test_memory_leaks_error_conditions() {
2176            let mut tracker = DropTracker::new();
2177
2178            let mut list = SingleLinkedList::new();
2179            for i in 0..10 {
2180                list.push_back(tracker.track(i));
2181            }
2182
2183            assert_eq!(tracker.alive().count(), 10, "10 elements should be alive");
2184
2185            // Попытка удаления по неверному индексу (не должна вызывать утечек)
2186            assert!(list.remove(15).is_err());
2187
2188            // Попытка вставки по неверному индексу
2189            assert!(list.insert(15, tracker.track(99)).is_err());
2190
2191            assert_eq!(
2192                tracker.alive().count(),
2193                10,
2194                "10 elements should be alive (10 original + 1 attempted insert)"
2195            );
2196
2197            // Очищаем список
2198            while list.len() > 0 {
2199                let _ = list.pop_front();
2200            }
2201
2202            drop(list); // Явное удаление
2203
2204            assert_eq!(
2205                tracker.alive().count(),
2206                0,
2207                "All elements should be dropped even after error conditions"
2208            );
2209            assert_eq!(
2210                tracker.dropped().count(),
2211                11,
2212                "All 11 elements should have been dropped"
2213            );
2214        }
2215
2216        // Test that clear() properly frees all nodes and there's no memory leak
2217        #[test]
2218        fn test_clear_no_memory_leak_with_drop_tracker() {
2219            // Create a list with tracked nodes
2220            let mut list = SingleLinkedList::new();
2221            let mut tracker = DropTracker::new();
2222
2223            // Add several elements — each will be wrapped in DropTracker
2224            list.push_back(tracker.track(10));
2225            list.push_back(tracker.track(20));
2226            list.push_back(tracker.track(30));
2227            list.push_back(tracker.track(40));
2228            list.push_back(tracker.track(50));
2229
2230            assert_eq!(list.len(), 5, "list should have 5 elements before clear()");
2231            assert_eq!(tracker.alive().count(), 5, "no nodes should be dropped yet");
2232
2233            // Clear the list — all nodes should be freed and their Drop impl called
2234            list.clear();
2235
2236            assert!(list.is_empty(), "list should be empty after clear()");
2237            assert_eq!(list.len(), 0, "length should be 0 after clear()");
2238            assert_eq!(
2239                tracker.alive().count(),
2240                0,
2241                "all 5 nodes should be dropped during clear()"
2242            );
2243
2244            assert_eq!(
2245                tracker.dropped().count(),
2246                5,
2247                "no additional drops should happen after list destruction"
2248            );
2249        }
2250
2251        // Test memory cleanup when clear() is called on a list with complex types
2252        #[test]
2253        fn test_clear_complex_types_no_memory_leak() {
2254            let mut list = SingleLinkedList::new();
2255            let mut tracker = DropTracker::new();
2256
2257            // Use DropTracker with String type
2258            list.push_back(tracker.track("first".to_string()));
2259            list.push_back(tracker.track("second".to_string()));
2260            list.push_back(tracker.track("third".to_string()));
2261
2262            assert_eq!(list.len(), 3, "complex type list should have correct size");
2263            assert_eq!(tracker.alive().count(), 3, "no drops before clear()");
2264
2265            list.clear();
2266
2267            assert!(
2268                list.is_empty(),
2269                "complex type list should be empty after clear()"
2270            );
2271            assert_eq!(
2272                tracker.alive().count(),
2273                0,
2274                "all 3 complex nodes should be dropped during clear()"
2275            );
2276
2277            assert_eq!(
2278                tracker.dropped().count(),
2279                3,
2280                "no extra drops after complex list destruction"
2281            );
2282        }
2283
2284        // Test that clear() works correctly even if some nodes were already dropped
2285        // through other operations
2286        #[test]
2287        fn test_clear_after_partial_removal_no_leak() {
2288            let mut list = SingleLinkedList::new();
2289            let mut tracker = DropTracker::new();
2290
2291            // Add 4 elements
2292            list.push_back(tracker.track(1));
2293            list.push_back(tracker.track(2));
2294            list.push_back(tracker.track(3));
2295            list.push_back(tracker.track(4));
2296
2297            assert_eq!(list.len(), 4, "initial list size should be 4");
2298            assert_eq!(tracker.alive().count(), 4, "no drops at start");
2299
2300            // Remove two elements manually
2301            let _ = list.pop_front(); // drops element 1
2302            let _ = list.pop_back(); // drops element 4
2303
2304            assert_eq!(list.len(), 2, "list size should be 2 after partial removal");
2305            assert_eq!(
2306                tracker.alive().count(),
2307                2,
2308                "2 nodes should be dropped by pop_front and pop_back"
2309            );
2310            assert_eq!(
2311                tracker.dropped().count(),
2312                2,
2313                "2 nodes should be dropped by pop_front and pop_back"
2314            );
2315
2316            // Now clear the remaining two elements
2317            list.clear();
2318
2319            assert!(list.is_empty(), "list should be empty after final clear()");
2320            assert_eq!(
2321                tracker.alive().count(),
2322                0,
2323                "total 4 nodes should be dropped (2 by pop, 2 by clear)"
2324            );
2325
2326            assert_eq!(
2327                tracker.dropped().count(),
2328                4,
2329                "no extra drops after list destruction"
2330            );
2331        }
2332    }
2333}