dsa/data_structures/linked_list.rs
1use crate::data_structures::node::Node;
2
3/// A singly-linked list.
4///
5/// This structure represents a `LinkedList` where each node stores
6/// a value of type `T` and links to the next node in the sequence.
7pub struct LinkedList<T> {
8 /// The head node of the `LinkedList`,
9 /// or `None` if the list is empty.
10 head: Option<Box<Node<T>>>
11}
12
13impl<T> LinkedList<T> {
14 /// Creates a new and empty `LinkedList`.
15 ///
16 /// # Examples
17 ///
18 /// ```
19 /// use dsa::data_structures::linked_list::LinkedList;
20 ///
21 /// let list: LinkedList<i32> = LinkedList::new();
22 /// assert!(list.is_empty());
23 /// ```
24 pub fn new() -> Self {
25 LinkedList { head: None }
26 }
27
28 /// Adds a value to the front of the `LinkedList`.
29 ///
30 /// This method creates a new node containing the given value
31 /// and makes it the new head of the list.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// use dsa::data_structures::linked_list::LinkedList;
37 ///
38 /// let mut list = LinkedList::new();
39 /// list.push_front(10);
40 /// list.push_front(20);
41 /// assert!(!list.is_empty());
42 /// ```
43 pub fn push_front(&mut self, value: T) {
44 let mut new_node = Box::new(
45 Node::new(
46 value,
47 None
48 )
49 );
50
51 new_node.next = self.head.take();
52 self.head = Some(new_node);
53 }
54
55 /// Removes and returns the value from the front of the `LinkedList`.
56 ///
57 /// If the list is empty, this method returns `None`. Otherwise,
58 /// it removes the head node and returns its value.
59 ///
60 ///
61 /// # Returns
62 /// An `Option<T>` optional generic type based on whether the topmost node was popped
63 /// from the list
64 /// - `Some` node is returned if this `LinkedList` has a head, otherwise `None`
65 ///
66 /// # Examples
67 ///
68 /// ```
69 /// use dsa::data_structures::linked_list::LinkedList;
70 ///
71 /// let mut list = LinkedList::new();
72 ///
73 /// list.push_front(10);
74 /// list.push_front(20);
75 /// assert_eq!(list.pop_front(), Some(20));
76 /// assert_eq!(list.pop_front(), Some(10));
77 /// assert!(list.is_empty());
78 /// ```
79 pub fn pop_front(&mut self) -> Option<T> {
80 if let Some(node) = self.head.take() {
81 self.head = node.next;
82 Some(node.value)
83 } else {
84 None
85 }
86 }
87
88 /// Checks whether the `LinkedList` is empty.
89 ///
90 /// # Returns
91 /// A `bool`, `true` or `false`, based on whether this `LinkedList` is
92 /// empty
93 ///
94 /// # Examples
95 ///
96 /// ```
97 /// use dsa::data_structures::linked_list::LinkedList;
98 ///
99 /// let mut list = LinkedList::new();
100 /// assert!(list.is_empty());
101 /// list.push_front(10);
102 /// assert!(!list.is_empty());
103 /// ```
104 pub fn is_empty(&self) -> bool {
105 self.head.is_none()
106 }
107}