All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0206_reverse_linked_list.Solution.rs Maven / Gradle / Ivy

There is a newer version: 1.8
Show newest version
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Linked_List #Recursion
// #Data_Structure_I_Day_8_Linked_List #Algorithm_I_Day_10_Recursion_Backtracking
// #Level_1_Day_3_Linked_List #Udemy_Linked_List #Big_O_Time_O(N)_Space_O(1)
// #2024_09_10_Time_0_ms_(100.00%)_Space_2.5_MB_(14.14%)

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option>
// }
// 
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    pub fn reverse_list(mut head: Option>) -> Option> {
        let mut prev: Option> = None;
        let mut curr = head;

        while let Some(mut node) = curr {
            curr = node.next.take(); // Move the next node to curr
            node.next = prev;        // Reverse the current node's next pointer
            prev = Some(node);       // Move prev forward to the current node
        }

        prev
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy