题解 | #合并两个排序的链表# | Rust
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct ListNode { * pub val: i32, * pub next: Option<Box<ListNode>> * } * * impl ListNode { * #[inline] * fn new(val: i32) -> Self { * ListNode { * val: val, * next: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ pub fn Merge(&self, pHead1: Option<Box<ListNode>>, pHead2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { // write code here if pHead1 == None { return pHead2; } if pHead2 == None { return pHead1; } let mut ans : Option<Box<ListNode>> = None; if pHead1.as_ref().unwrap().val < pHead2.as_ref().unwrap().val { ans = pHead1; ans.as_mut().unwrap().next = Solution::Merge(self, ans.as_mut().unwrap().next.take(), pHead2); } else { ans = pHead2; ans.as_mut().unwrap().next = Solution::Merge(self, pHead1, ans.as_mut().unwrap().next.take()); } return ans; } }