circular_doubly_linked_list 0.1.0

A high-performance Circular Doubly Linked List implementation in Rust
Documentation
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! List module containing the main Circular Doubly Linked List implementation.
//!
//! This module provides the `CircularDoublyLinkedList` struct which is the
//! primary public API for interacting with the data structure. All unsafe
//! operations are encapsulated within safe methods.
//!
//! # Design Decisions
//!
//! This implementation maintains both `head` and `tail` pointers for:
//! - **O(1)** access to both front and back elements
//! - **O(1)** insertion at both ends without pointer traversal
//! - Clearer semantic meaning for list boundaries
//!
//! # Invariants
//!
//! The following invariants are maintained throughout the list's lifetime:
//! - If the list is non-empty, both `head` and `tail` point to valid nodes
//! - If the list is empty, both `head` and `tail` are `None`
//! - If the list has one element, `head == tail`
//! - If the list has multiple elements:
//!   - `tail.next == head` (circular forward link)
//!   - `head.prev == tail` (circular backward link)
//! - The `length` field accurately reflects the number of nodes

use core::ptr::NonNull;

use crate::iter::{IntoIter, Iter, IterMut};
use crate::node::Node;

/// A circular doubly linked list with explicit head and tail pointers.
///
/// This data structure provides O(1) insertion and deletion at both ends,
/// with safe APIs that wrap unsafe pointer operations internally. The circular
/// nature means the last node points back to the first, and vice versa.
///
/// # Type Parameters
///
/// * `T` - The type of elements stored in the list
///
/// # Examples
///
/// ```rust
/// use circular_doubly_linked_list::CircularDoublyLinkedList;
///
/// let mut list = CircularDoublyLinkedList::new();
/// list.push_back(1);
/// list.push_back(2);
/// list.push_front(0);
///
/// assert_eq!(list.len(), 3);
/// assert_eq!(list.front(), Some(&0));
/// assert_eq!(list.back(), Some(&2));
/// ```
///
/// # Safety
///
/// While the public API is safe, the internal implementation uses raw pointers.
/// The list maintains the following invariants:
/// - If the list is non-empty, `head` and `tail` point to valid nodes
/// - All nodes form a proper circular chain
/// - The length accurately reflects the number of nodes
/// - No node is ever accessed after deallocation
pub struct CircularDoublyLinkedList<T> {
    /// Pointer to the head node (front of the list).
    ///
    /// This points to the first element inserted via `push_front` or the
    /// first element when using only `push_back`.
    ///
    /// # Invariants
    ///
    /// - `None` if and only if the list is empty
    /// - Points to a valid allocated `Node<T>` when non-empty
    /// - `head.prev` always points to the tail node (when non-empty)
    head: Option<NonNull<Node<T>>>,

    /// Pointer to the tail node (back of the list).
    ///
    /// This points to the last element inserted via `push_back` or the
    /// last element in the logical order of the list.
    ///
    /// # Invariants
    ///
    /// - `None` if and only if the list is empty
    /// - Points to a valid allocated `Node<T>` when non-empty
    /// - `tail.next` always points to the head node (when non-empty)
    /// - When `length == 1`, `tail == head`
    tail: Option<NonNull<Node<T>>>,

    /// The number of elements in the list.
    ///
    /// This is cached to provide O(1) length queries without traversal.
    ///
    /// # Invariants
    ///
    /// - Always equals the actual number of allocated nodes
    /// - Zero if and only if `head` and `tail` are both `None`
    length: usize,
}

impl<T> CircularDoublyLinkedList<T> {
    /// Creates a new empty circular doubly linked list.
    ///
    /// # Returns
    ///
    /// Returns a new empty `CircularDoublyLinkedList` with `head` and `tail`
    /// set to `None` and `length` set to 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let list: CircularDoublyLinkedList<i32> = CircularDoublyLinkedList::new();
    /// assert!(list.is_empty());
    /// assert_eq!(list.len(), 0);
    /// assert_eq!(list.front(), None);
    /// assert_eq!(list.back(), None);
    /// ```
    pub fn new() -> Self {
        Self {
            head: None,
            tail: None,
            length: 0,
        }
    }

    /// Returns the number of elements in the list.
    ///
    /// # Returns
    ///
    /// Returns the length of the list as `usize`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// assert_eq!(list.len(), 0);
    ///
    /// list.push_back(1);
    /// list.push_back(2);
    /// assert_eq!(list.len(), 2);
    ///
    /// list.push_front(0);
    /// assert_eq!(list.len(), 3);
    /// ```
    pub fn len(&self) -> usize {
        self.length
    }

    /// Returns `true` if the list contains no elements.
    ///
    /// # Returns
    ///
    /// Returns `true` if the list is empty (length is 0), `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// assert!(list.is_empty());
    ///
    /// list.push_back(1);
    /// assert!(!list.is_empty());
    ///
    /// list.pop_back();
    /// assert!(list.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.length <= 0
    }

    /// Returns a reference to the front element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(&T)` containing a reference to the front element if the
    /// list is non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// assert_eq!(list.front(), None);
    ///
    /// list.push_front(42);
    /// assert_eq!(list.front(), Some(&42));
    ///
    /// list.push_front(100);
    /// assert_eq!(list.front(), Some(&100));
    /// ```
    pub fn front(&self) -> Option<&T> {
        self.head.map(|head| unsafe { Node::data_ref(head) })
    }

    /// Returns a mutable reference to the front element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(&mut T)` containing a mutable reference to the front
    /// element if the list is non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_front(42);
    ///
    /// if let Some(front) = list.front_mut() {
    ///     *front = 100;
    /// }
    ///
    /// assert_eq!(list.front(), Some(&100));
    /// ```
    pub fn front_mut(&mut self) -> Option<&mut T> {
        self.head.map(|head| unsafe { Node::data_mut(head) })
    }

    /// Returns a reference to the back element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(&T)` containing a reference to the back element if the
    /// list is non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// assert_eq!(list.back(), None);
    ///
    /// list.push_back(42);
    /// assert_eq!(list.back(), Some(&42));
    ///
    /// list.push_back(100);
    /// assert_eq!(list.back(), Some(&100));
    /// ```
    pub fn back(&self) -> Option<&T> {
        self.tail.map(|tail| unsafe { Node::data_ref(tail) })
    }

    /// Returns a mutable reference to the back element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(&mut T)` containing a mutable reference to the back
    /// element if the list is non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(42);
    ///
    /// if let Some(back) = list.back_mut() {
    ///     *back = 100;
    /// }
    ///
    /// assert_eq!(list.back(), Some(&100));
    /// ```
    pub fn back_mut(&mut self) -> Option<&mut T> {
        self.tail.map(|tail| unsafe { Node::data_mut(tail) })
    }

    /// Inserts an element at the front of the list.
    ///
    /// After this operation, the new element becomes the front element and
    /// can be accessed via `front()` or `front_mut()`.
    ///
    /// # Parameters
    ///
    /// * `value` - The value to insert at the front
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_front(1);
    /// list.push_front(2);
    /// list.push_front(3);
    ///
    /// assert_eq!(list.front(), Some(&3));
    /// assert_eq!(list.back(), Some(&1));
    /// assert_eq!(list.len(), 3);
    /// ```
    pub fn push_front(&mut self, value: T) {
        let new_node = Node::new(value);

        unsafe {
            match (self.head, self.tail) {
                (None, None) => {
                    self.head = Some(new_node);
                    self.tail = Some(new_node);
                }
                (Some(head), Some(tail)) => {
                    Node::set_next(new_node, head);
                    Node::set_prev(new_node, tail);
                    Node::set_prev(head, new_node);
                    Node::set_next(tail, new_node);
                    self.head = Some(new_node);
                }
                _ => unreachable!("head and tail must both be None or both be Some"),
            }
        }

        self.length += 1;
    }

    /// Inserts an element at the back of the list.
    ///
    /// After this operation, the new element becomes the back element and
    /// can be accessed via `back()` or `back_mut()`.
    ///
    /// # Parameters
    ///
    /// * `value` - The value to insert at the back
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// assert_eq!(list.front(), Some(&1));
    /// assert_eq!(list.back(), Some(&3));
    /// assert_eq!(list.len(), 3);
    /// ```
    pub fn push_back(&mut self, value: T) {
        let new_node = Node::new(value);

        unsafe {
            match (self.head, self.tail) {
                (None, None) => {
                    self.head = Some(new_node);
                    self.tail = Some(new_node);
                }
                (Some(head), Some(tail)) => {
                    Node::set_next(new_node, head);
                    Node::set_prev(new_node, tail);
                    Node::set_next(tail, new_node);
                    Node::set_prev(head, new_node);
                    self.tail = Some(new_node);
                }
                _ => unreachable!("head and tail must both be None or both be Some"),
            }
        }

        self.length += 1;
    }

    /// Removes and returns the front element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(T)` containing the removed front element if the list is
    /// non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_front(1);
    /// list.push_front(2);
    ///
    /// assert_eq!(list.pop_front(), Some(2));
    /// assert_eq!(list.pop_front(), Some(1));
    /// assert_eq!(list.pop_front(), None);
    /// ```
    pub fn pop_front(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        unsafe {
            let head = self.head?;
            let tail = self.tail?;
            let next = Node::get_next(head);

            let result = if self.length == 1 {
                self.head = None;
                self.tail = None;
                Some(Node::dealloc(head))
            } else {
                Node::set_next(tail, next);
                Node::set_prev(next, tail);
                self.head = Some(next);
                Some(Node::dealloc(head))
            };

            self.length -= 1;
            result
        }
    }

    /// Removes and returns the back element of the list.
    ///
    /// # Returns
    ///
    /// Returns `Some(T)` containing the removed back element if the list is
    /// non-empty, or `None` if the list is empty.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// assert_eq!(list.pop_back(), Some(2));
    /// assert_eq!(list.pop_back(), Some(1));
    /// assert_eq!(list.pop_back(), None);
    /// ```
    pub fn pop_back(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }

        unsafe {
            let head = self.head?;
            let tail = self.tail?;
            let prev = Node::get_prev(tail);

            let result = if self.length == 1 {
                self.head = None;
                self.tail = None;
                Some(Node::dealloc(tail))
            } else {
                Node::set_next(prev, head);
                Node::set_prev(head, prev);
                self.tail = Some(prev);
                Some(Node::dealloc(tail))
            };

            self.length -= 1;
            result
        }
    }

    /// Inserts an element after the given position.
    ///
    /// # Parameters
    ///
    /// * `position` - The index after which to insert (0-based). Valid range: `0..length-1`
    /// * `value` - The value to insert
    ///
    /// # Returns
    ///
    /// Returns `true` if insertion was successful, or `false` if the position
    /// is out of bounds (position >= length).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(3);
    ///
    /// assert!(list.insert_after(0, 2));
    ///
    /// let vec: Vec<_> = list.iter().copied().collect();
    /// assert_eq!(vec, [1, 2, 3]);
    ///
    /// // Invalid position
    /// assert!(!list.insert_after(10, 4));
    /// ```
    pub fn insert_after(&mut self, position: usize, value: T) -> bool {
        if position >= self.length {
            return false;
        }

        let target_node = unsafe { self.get_node_at(position).unwrap() };

        unsafe {
            let new_node = Node::new(value);
            let next = Node::get_next(target_node);

            Node::set_next(new_node, next);
            Node::set_prev(new_node, target_node);
            Node::set_next(target_node, new_node);
            Node::set_prev(next, new_node);

            if Some(target_node) == self.tail {
                self.tail = Some(new_node);
            }
        }

        self.length += 1;
        true
    }

    /// Removes the element at the given position.
    ///
    /// # Parameters
    ///
    /// * `position` - The index of the element to remove (0-based)
    ///
    /// # Returns
    ///
    /// Returns `Some(T)` containing the removed element if the position is
    /// valid, or `None` if the position is out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// assert_eq!(list.remove_at(1), Some(2));
    ///
    /// let vec: Vec<_> = list.iter().copied().collect();
    /// assert_eq!(vec, [1, 3]);
    ///
    /// // Invalid position
    /// assert_eq!(list.remove_at(10), None);
    /// ```
    pub fn remove_at(&mut self, position: usize) -> Option<T> {
        if self.is_empty() || position >= self.length {
            return None;
        }

        let target_node = unsafe { self.get_node_at(position)? };
        unsafe {
            let next = Node::get_next(target_node);
            let prev = Node::get_prev(target_node);

            if Some(target_node) == self.head {
                self.head = Some(next);
            }

            if Some(target_node) == self.tail {
                self.tail = Some(prev)
            }

            if self.length == 1 {
                self.head = None;
                self.tail = None;
            } else {
                Node::set_next(prev, next);
                Node::set_prev(next, prev);
            }

            self.length -= 1;
            Some(Node::dealloc(target_node))
        }
    }

    /// Clears all elements from the list.
    ///
    /// After this operation, the list will be empty with `head` and `tail`
    /// set to `None` and `length` set to 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// list.clear();
    ///
    /// assert!(list.is_empty());
    /// assert_eq!(list.len(), 0);
    /// assert_eq!(list.front(), None);
    /// assert_eq!(list.back(), None);
    /// ```
    pub fn clear(&mut self) {
        while self.pop_front().is_some() {}
    }

    /// Returns an iterator over the list.
    ///
    /// # Returns
    ///
    /// Returns an `Iter<T>` that yields immutable references to elements
    /// in order from front to back.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// for item in list.iter() {
    ///     println!("{}", item);
    /// }
    /// // Output: 1, 2, 3
    /// ```
    pub fn iter(&self) -> Iter<'_, T> {
        Iter::new(self.head, self.length)
    }

    /// Returns an iterator over the list with mutable references.
    ///
    /// # Returns
    ///
    /// Returns an `IterMut<T>` that yields mutable references to elements
    /// in order from front to back.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// for item in list.iter_mut() {
    ///     *item *= 2;
    /// }
    ///
    /// let vec: Vec<_> = list.iter().copied().collect();
    /// assert_eq!(vec, [2, 4]);
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut::new(self.head, self.length)
    }

    /// Rotates the list by moving the front element to the back.
    ///
    /// This operation is O(1) because it only updates the head and tail
    /// pointers without moving any data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// list.rotate_left();
    ///
    /// let vec: Vec<_> = list.iter().copied().collect();
    /// assert_eq!(vec, [2, 3, 1]);
    /// ```
    pub fn rotate_left(&mut self) {
        if self.length > 1 {
            unsafe {
                let head = self.head.unwrap();
                let new_head = Node::get_next(head);
                let new_tail = head;

                self.head = Some(new_head);
                self.tail = Some(new_tail);
            }
        }
    }

    /// Rotates the list by moving the back element to the front.
    ///
    /// This operation is O(1) because it only updates the head and tail
    /// pointers without moving any data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// list.rotate_right();
    ///
    /// let vec: Vec<_> = list.iter().copied().collect();
    /// assert_eq!(vec, [3, 1, 2]);
    /// ```
    pub fn rotate_right(&mut self) {
        if self.length > 1 {
            unsafe {
                let tail = self.tail.unwrap();
                let new_head = tail;
                let new_tail = Node::get_prev(tail);

                self.head = Some(new_head);
                self.tail = Some(new_tail);
            }
        }
    }

    /// Internal helper to get a node at a specific position.
    ///
    /// # Parameters
    ///
    /// * `position` - The 0-based index of the node to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Some(NonNull<Node<T>>)` if the position is valid, `None` otherwise.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - The list is not empty
    /// - The position is within bounds (position < length)
    ///
    /// # Optimization
    ///
    /// This method traverses from the closer end (head or tail) to minimize
    /// the number of pointer dereferences.
    unsafe fn get_node_at(&self, position: usize) -> Option<NonNull<Node<T>>> {
        if self.is_empty() || position >= self.length {
            return None;
        }

        if position < self.length / 2 {
            let mut current = self.head?;

            for _ in 0..position {
                current = unsafe { Node::get_next(current) }
            }
            Some(current)
        } else {
            let mut current = self.tail?;
            for _ in position + 1..self.length {
                current = unsafe { Node::get_prev(current) }
            }
            Some(current)
        }
    }
}

impl<T> Default for CircularDoublyLinkedList<T> {
    /// Creates a default (empty) circular doubly linked list.
    ///
    /// # Returns
    ///
    /// Returns a new empty `CircularDoublyLinkedList`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let list: CircularDoublyLinkedList<i32> = CircularDoublyLinkedList::default();
    /// assert!(list.is_empty());
    /// ```
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Drop for CircularDoublyLinkedList<T> {
    /// Drops the list and deallocates all nodes.
    ///
    /// This ensures all allocated memory is properly freed when the list
    /// goes out of scope.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// {
    ///     let mut list = CircularDoublyLinkedList::new();
    ///     list.push_back(1);
    ///     list.push_back(2);
    ///     // List is automatically dropped here
    /// }
    /// ```
    fn drop(&mut self) {
        self.clear();
    }
}

impl<T> Clone for CircularDoublyLinkedList<T>
where
    T: Clone,
{
    /// Creates a deep copy of the list.
    ///
    /// # Returns
    ///
    /// Returns a new `CircularDoublyLinkedList` with cloned elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// let cloned = list.clone();
    ///
    /// assert_eq!(list.len(), cloned.len());
    /// assert!(list.iter().eq(cloned.iter()));
    /// ```
    fn clone(&self) -> Self {
        let mut new_list = CircularDoublyLinkedList::<T>::new();
        for item in self.iter() {
            new_list.push_back(item.clone());
        }
        new_list
    }
}

impl<T> Extend<T> for CircularDoublyLinkedList<T> {
    /// Extends the list with elements from an iterator.
    ///
    /// # Parameters
    ///
    /// * `iter` - An iterator yielding elements to add
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.extend(vec![1, 2, 3]);
    ///
    /// assert_eq!(list.len(), 3);
    /// ```
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for item in iter {
            self.push_back(item);
        }
    }
}

impl<T: core::fmt::Debug> core::fmt::Debug for CircularDoublyLinkedList<T> {
    /// Formats the list for debugging.
    ///
    /// # Parameters
    ///
    /// * `f` - The formatter to write to
    ///
    /// # Returns
    ///
    /// Returns a `Result` indicating success or failure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// println!("{:?}", list);
    /// // Output: [1, 2]
    /// ```
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<T> FromIterator<T> for CircularDoublyLinkedList<T> {
    /// Creates a list from an iterator.
    ///
    /// # Parameters
    ///
    /// * `iter` - An iterator yielding elements
    ///
    /// # Returns
    ///
    /// Returns a new `CircularDoublyLinkedList` containing all elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let list: CircularDoublyLinkedList<i32> = vec![1, 2, 3].into_iter().collect();
    ///
    /// assert_eq!(list.len(), 3);
    /// ```
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut list = CircularDoublyLinkedList::<T>::new();
        list.extend(iter);
        list
    }
}

impl<T> IntoIterator for CircularDoublyLinkedList<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    /// Consumes the list and returns an iterator over its elements.
    ///
    /// # Returns
    ///
    /// Returns an `IntoIter<T>` that yields owned values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// for item in list.into_iter() {
    ///     println!("{}", item);
    /// }
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        let iter = IntoIter::new(self.head, self.length);
        core::mem::forget(self);
        iter
    }
}

impl<'a, T> IntoIterator for &'a CircularDoublyLinkedList<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    /// Returns an iterator over immutable references.
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut CircularDoublyLinkedList<T> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

    /// Returns an iterator over mutable references.
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}