题目解析
新建一个 Node,对需要合并的两个 Node 迭代遍历,比较两个 Node 的大小,然后指向小的一测,一直到底。
pub fn merge_two_lists(mut l1: Option<Box<ListNode>>,mut l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut l3 = ListNode::new(0);
let mut ptr3 = &mut l3;
while let (Some(n1), Some(n2)) = (l1.as_ref(),l2.as_ref()) {
if n1.val < n2.val {
ptr3.next = l1;
ptr3 = ptr3.next.as_mut().unwrap();
l1 = ptr3.next.take();
}else {
ptr3.next = l2;
ptr3 = ptr3.next.as_mut().unwrap();
l2 = ptr3.next.take();
}
}
//剩余部分
ptr3.next = if l1.is_some() { l1 } else { l2 };
l3.next
}
复杂度分析:
时间复杂度: O(n+m)。
空间复杂度: O(n+m)。