对于新链表的每个节点,我直接new新的节点,不复用之前的。
```rust
impl Solution {
pub fn merge_two_lists(list1: Option<Box<ListNode>>,
list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy_head = Box::new(ListNode::new(-1));
let mut dummy_head1 = Box::new(ListNode::new(-1));
let mut dummy_head2 = Box::new(ListNode::new(-1));
dummy_head1.next = list1;
dummy_head2.next = list2;
let mut tail = &mut dummy_head;
let mut l1 = &mut dummy_head1;
let mut l2 = &mut dummy_head2;
while l1.next.is_some() && l2.next.is_some() {
let x = l1.next.as_ref().unwrap().val;
let y = l2.next.as_ref().unwrap().val;
if x < y {
tail.next = Some(Box::new(ListNode::new(x)));
tail = tail.next.as_mut().unwrap();
l1 = l1.next.as_mut().unwrap();
}
else {
tail.next = Some(Box::new(ListNode::new(y)));
tail = tail.next.as_mut().unwrap();
l2 = l2.next.as_mut().unwrap();
}
}
if l1.next.is_some() {
tail.next = l1.next.take();
}
else if l2.next.is_some() {
tail.next = l2.next.take();
}
return dummy_head.next;
}
}
```
当Rust遇上LeetCode #21. 合并两个有序链表 [简单]2020/2/17 题目描述 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例 相关标签 链表 解题思路 递归法算法:特殊的...