Rust ListNode与Vec互转测试函数

This commit is contained in:
游由 2021-11-18 09:42:09 +08:00
parent 1aff9a97cc
commit 6b0a1eeebe
3 changed files with 31 additions and 10 deletions

View File

@ -51,10 +51,10 @@ mod test {
#[test]
fn test_q0021() {
let l1 = Some(Box::new(ListNode { val: 1, next: Some(Box::new(ListNode { val: 2, next: Some(Box::new(ListNode { val: 4, next: None })) })) }));
let l2 = Some(Box::new(ListNode { val: 1, next: Some(Box::new(ListNode { val: 3, next: Some(Box::new(ListNode { val: 4, next: None })) })) }));
let merge = Solution::merge_two_lists(l1, l2);
let ans = Some(Box::new(ListNode { val: 1, next: Some(Box::new(ListNode { val: 1, next: Some(Box::new(ListNode { val: 2, next: Some(Box::new(ListNode { val: 3, next: Some(Box::new(ListNode { val: 4, next: Some(Box::new(ListNode { val: 4, next: None })) })) })) })) })) }));
let l1 = ListNode::from_vec(vec![1, 2, 4]);
let l2 = ListNode::from_vec(vec![1, 3, 4]);
let ans = Solution::merge_two_lists(l1, l2);
let merge = ListNode::from_vec(vec![1, 1, 2, 3, 4, 4]);
assert_eq!(merge, ans);
}
}

View File

@ -47,12 +47,8 @@ mod test {
#[test]
fn test_q0876() {
let list = Some(Box::new(ListNode { val: 1, next:
Some(Box::new(ListNode { val: 3, next:
Some(Box::new(ListNode { val: 5, next:
Some(Box::new(ListNode { val: 7, next:
Some(Box::new(ListNode { val: 9, next: None })) })) })) })) }));
let list = ListNode::from_vec(vec![1, 3, 5, 7, 9]);
let option = Solution::middle_node(list);
assert_eq!(option.unwrap().val, 5);
assert_eq!(vec![5, 7, 9], ListNode::to_vec(option));
}
}

View File

@ -20,6 +20,31 @@ impl ListNode {
}
}
#[cfg(test)]
mod test {
use crate::structure::ListNode;
impl ListNode {
pub(crate) fn from_vec(vec: Vec<i32>) -> Option<Box<ListNode>> {
let mut node = None;
for val in vec.into_iter().rev() {
node = Some(Box::new(ListNode { val, next: node }));
}
node
}
//noinspection RsSelfConvention
pub(crate) fn to_vec(mut list: Option<Box<ListNode>>) -> Vec<i32> {
let mut ret = vec![];
while let Some(n) = list {
ret.push(n.val);
list = n.next;
}
ret
}
}
}
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {