Skip to content

Instantly share code, notes, and snippets.

@akr4
Last active September 15, 2019 02:52
Show Gist options
  • Save akr4/d2836be9ae7d9d370f16889408b20b66 to your computer and use it in GitHub Desktop.
Save akr4/d2836be9ae7d9d370f16889408b20b66 to your computer and use it in GitHub Desktop.
list! macro for ListNode on leetcode
#[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