evillatoro_data_structures/
doubly_linked_list.rs

1pub struct DoublyLinkedList<T> {
2    pub head: Option<Box<ListNode<T>>>,
3    pub length: usize,
4}
5
6impl<T> DoublyLinkedList<T> {
7    /// Creates a new empty `DoublyLinkedList`.
8    ///
9    /// # Examples
10    /// ```
11    /// use data_structures::doubly_linked_list::DoublyLinkedList;
12    /// struct T;
13    /// let list:DoublyLinkedList<T> = DoublyLinkedList::new();
14    /// assert!(list.is_empty());
15    /// ````
16    pub fn new() -> DoublyLinkedList<T> {
17        DoublyLinkedList {
18            head: None,
19            length: 0,
20        }
21    }
22
23    /// Creates a new `DoublyLinkedList` initialized with a single element.
24    ///
25    /// # Parameters
26    ///
27    /// - `data`: The initial value for the first node in the list.
28    ///
29    /// # Examples
30    ///
31    /// ```
32    /// use data_structures::doubly_linked_list::DoublyLinkedList;
33    /// let list = DoublyLinkedList::with_value(42);
34    /// assert_eq!(list.length, 1);
35    /// ```
36    pub fn with_value(data: T) -> DoublyLinkedList<T> {
37        let new_node = Box::new(ListNode::new(data));
38        DoublyLinkedList {
39            head: Some(new_node),
40            length: 1,
41        }
42    }
43
44    /// Checks if the `DoublyLinkedList` is empty.
45    ///
46    /// # Returns
47    /// `true` if the list has no elements, and `false` otherwise
48    ///
49    /// # Examples
50    /// ```
51    /// use data_structures::doubly_linked_list::DoublyLinkedList;
52    ///
53    /// let empty_list: DoublyLinkedList<i32> = DoublyLinkedList::new();
54    /// assert!(empty_list.is_empty());
55    ///
56    /// let list: DoublyLinkedList<i32> = DoublyLinkedList::with_value(30);
57    /// assert!(!list.is_empty());
58    /// ```
59    pub fn is_empty(&self) -> bool {
60        self.length == 0
61    }
62}
63
64pub struct ListNode<T> {
65    next: Option<Box<ListNode<T>>>,
66    pub data: T,
67}
68
69impl<T> ListNode<T> {
70    pub fn new(data: T) -> ListNode<T> {
71        ListNode { data, next: None }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77
78    mod doubly_linked_list {
79        use crate::doubly_linked_list::DoublyLinkedList;
80
81        #[test]
82        fn test_new() {
83            let list: DoublyLinkedList<bool> = DoublyLinkedList::new();
84            assert!(list.is_empty())
85        }
86
87        fn test_with_value() {
88            let list: DoublyLinkedList<bool> = DoublyLinkedList::with_value(true);
89            assert!(!list.is_empty())
90        }
91
92    }
93}