id 1378821029 Time: 1 ms MemUsage: 2.1 MB

This commit is contained in:
2024-09-04 22:36:59 +09:00
parent 474b4aaf62
commit eb49696866

View File

@@ -0,0 +1,45 @@
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn merge_two_lists(
mut list1: Option<Box<ListNode>>,
mut list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut new_head = Box::new(ListNode::new(0));
let mut tail = &mut new_head;
while let (Some(unwrapped_list1),Some(unwrapped_list2)) = (list1.as_ref(),list2.as_ref()) {
if unwrapped_list1.val >= unwrapped_list2.val
{
tail.next = Some(Box::new(ListNode::new(unwrapped_list2.val)));
list2 = list2.as_mut().unwrap().next.take();
} else {
tail.next = Some(Box::new(ListNode::new(unwrapped_list1.val)));
list1 = list1.as_mut().unwrap().next.take();
}
tail = tail.next.as_mut().unwrap();
}
if list1.is_some(){
tail.next=list1;
}
else{
tail.next=list2;
}
return new_head.next;
}
}