Created
May 7, 2022 01:42
-
-
Save abekoh/b9782a706d103332f98e897d2874092d to your computer and use it in GitHub Desktop.
[Leetcode] ListNode constructor for Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 ListNode { | |
#[inline] | |
fn from(values: &[i32]) -> Option<Box<ListNode>> { | |
if values.is_empty() { | |
return None; | |
} | |
Some(Box::from(ListNode { | |
val: values[0], | |
next: Self::from(&values[1..]), | |
})) | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn from() { | |
assert_eq!( | |
ListNode::from(&vec![1, 2, 3]), | |
Some(Box::from(ListNode { | |
val: 1, | |
next: Some(Box::from(ListNode { | |
val: 2, | |
next: Some(Box::from(ListNode { val: 3, next: None })) | |
})) | |
})) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment