Skip to content

Instantly share code, notes, and snippets.

@abekoh
Created May 7, 2022 01:42
Show Gist options
  • Save abekoh/b9782a706d103332f98e897d2874092d to your computer and use it in GitHub Desktop.
Save abekoh/b9782a706d103332f98e897d2874092d to your computer and use it in GitHub Desktop.
[Leetcode] ListNode constructor for Rust
// 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