Merge Two Sorted Lists in Rust

impl Solution {
    pub fn merge_two_lists(
        list1: Option<Box<ListNode>>,
        list2: Option<Box<ListNode>>,
    ) -> Option<Box<ListNode>> {
        // Create a dummy head for the new list
        let mut dummy_head = ListNode::new(0);
        let mut tail = &mut dummy_head;

        // Mutable references to the current nodes of the two lists
        let mut list1 = list1;
        let mut list2 = list2;

        // Loop until either list is fully traversed
        while list1.is_some() && list2.is_some() {
            // Determine which list has the smaller current value
            let smaller_list = if list1.as_ref().unwrap().val < list2.as_ref().unwrap().val {
                &mut list1
            } else {
                &mut list2
            };

            // Move the smaller node to the new list
            tail.next = smaller_list.take();
            tail = tail.next.as_mut().unwrap();

            // Update the smaller list to point to the next node
            *smaller_list = tail.next.take();
        }

        // Attach the remaining elements of the non-exhausted list
        tail.next = if list1.is_some() { list1 } else { list2 };

        // Return the merged list, skipping the dummy head
        dummy_head.next
    }
}

PrevNext