Last active
September 15, 2019 02:52
-
-
Save akr4/d2836be9ae7d9d370f16889408b20b66 to your computer and use it in GitHub Desktop.
list! macro for ListNode on leetcode
This file contains hidden or 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
#[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 } | |
} | |
} | |
fn make_list(nodes: &[i32]) -> Option<Box<ListNode>> { | |
let ns: Vec<ListNode> = nodes.iter().rev().map(|x| ListNode::new(*x)).collect(); | |
let mut prev_node: Option<ListNode> = None; | |
for mut node in ns.into_iter() { | |
if let Some(n) = prev_node { | |
node.next = Some(Box::new(n)); | |
} | |
prev_node = Some(node); | |
} | |
prev_node.map(Box::new) | |
} | |
macro_rules! list { | |
($($x:expr),*) => { | |
make_list(&[$($x),*]) | |
}; | |
} | |
#[test] | |
fn test_make_list() { | |
let mut node = make_list(&[1, 2, 5]).unwrap(); | |
assert_eq!(1, node.val); | |
node = node.next.unwrap(); | |
assert_eq!(2, node.val); | |
node = node.next.unwrap(); | |
assert_eq!(5, node.val); | |
} | |
#[test] | |
fn test_list_macro() { | |
assert_eq!(make_list(&[1, 2, 3]), list![1, 2, 3]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment