Swap Nodes in Pairs in Rust

impl Solution {
    // Function to swap nodes in pairs in a linked list
    pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        // The `and_then` method is used to handle the Option
        // If `head` is None (i.e., the list is empty or we've reached the end of the list),
        // `and_then` will return None automatically.
        // If `head` is Some, it unwraps the Option for further processing.
        head.and_then(|mut first| {
            // `match` is used to destructure the `next` field of the first node
            match first.next {
                // If there is a second node, we proceed with the swapping
                Some(mut second) => {
                    // Recursively call `swap_pairs` for the rest of the list starting from the third node
                    // The result is assigned as the next node of the first node
                    first.next = Solution::swap_pairs(second.next);

                    // The first node becomes the next node of the second node
                    // Effectively swapping the first and second nodes
                    second.next = Some(first);

                    // Return the second node as the new head of this swapped pair
                    Some(second)
                }
                // If there is no second node, we just return the first node as is
                // This is the case when the list has an odd number of nodes or we're at the end of the list
                None => Some(first),
            }
        })
    }
}
impl Solution {
    pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        // Create a dummy head to simplify edge case handling
        let mut dummy = Box::new(ListNode::new(0));
        dummy.next = head;

        // Mutable reference to the current node, starting at dummy
        let mut current = &mut dummy;

        // Loop as long as the next two nodes exist
        while current.next.is_some() && current.next.as_ref().unwrap().next.is_some() {
            // Rust requires explicit temporary variables due to its ownership system
            // We temporarily take ownership of the next nodes to manipulate them
            let mut first = current.next.take().unwrap();
            let mut second = first.next.take().unwrap();

            // Swapping logic
            first.next = second.next.take();
            second.next = Some(first);
            current.next = Some(second);

            // Move current forward by two nodes
            current = current.next.as_mut().unwrap().next.as_mut().unwrap();
        }

        // Return the new head
        dummy.next
    }
}

PrevNext