Add Two Numbers in Rust

impl Solution {
    // A public function to add two numbers represented as reversed linked lists.
    // Each node in the list represents a single digit of the number.
    // l1 and l2 are the heads of the two linked lists.
    pub fn add_two_numbers(
        l1: Option<Box<ListNode>>,
        l2: Option<Box<ListNode>>,
    ) -> Option<Box<ListNode>> {
        // Create references to the heads of the two lists for traversal.
        // These pointers will move through each list without taking ownership.
        let (mut p1, mut p2) = (&l1, &l2);

        // Create a dummy head for the result linked list. This simplifies code by removing
        // the need to handle special cases for the head. The dummy head is removed at the end.
        let mut result_head = Some(Box::new(ListNode::new(0)));

        // Initialize the carry to 0. Carry is used for summing digits over 9.
        let mut carry = 0;

        // A mutable reference to traverse and build the resulting list.
        // It initially points to the dummy head.
        let mut current = &mut result_head;

        // Iterate until all nodes in both lists are consumed and no carry is left.
        while p1.is_some() || p2.is_some() || carry > 0 {
            // Calculate the sum of the current nodes and the carry.
            // Use pattern matching to handle different cases where the lists may not be of equal length.
            let sum = match (&p1, &p2) {
                // If both lists have a node, add their values and the carry.
                (Some(n1), Some(n2)) => n1.val + n2.val + carry,
                // If only one list has a node, add its value and the carry.
                (Some(n), None) | (None, Some(n)) => n.val + carry,
                // If both lists are empty, just use the carry.
                (None, None) => carry,
            };

            // Update the carry for the next iteration.
            // If the sum is 10 or more, carry will be 1, otherwise 0.
            carry = sum / 10;

            // Create a new node with the digit value of the sum and attach it to the result list.
            current.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum % 10)));

            // Move the pointers to the next nodes in their respective lists.
            if let Some(n) = p1 {
                // Here, &n.next is a reference to the next node (or None).
                // We update p1 to point to the next node without moving it out of the current one.
                p1 = &n.next;
            }
            if let Some(n) = p2 {
                // Same as above, for p2.
                p2 = &n.next;
            }

            // Move the current pointer to the next node in the result list.
            current = &mut current.as_mut().unwrap().next;
        }

        // Return the result list, skipping the dummy head.
        // Unwrap is safe here because we know result_head is not None.
        result_head.unwrap().next
    }
}

PrevNext