From 7a345fc66b8de2c4d90da8f99e843beffee11e88 Mon Sep 17 00:00:00 2001 From: rongyi Date: Thu, 12 Sep 2024 17:38:16 +0800 Subject: [PATCH] Idiomatic rust (#1505) --- codes/rust/include/list_node.rs | 16 ++++++++-------- codes/rust/include/tree_node.rs | 22 ++++++++++------------ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/codes/rust/include/list_node.rs b/codes/rust/include/list_node.rs index 68cf80414..003ab2989 100644 --- a/codes/rust/include/list_node.rs +++ b/codes/rust/include/list_node.rs @@ -29,7 +29,7 @@ impl ListNode { for item in array.iter().rev() { let node = Rc::new(RefCell::new(ListNode { val: *item, - next: head.clone(), + next: head.take(), })); head = Some(node); } @@ -44,14 +44,14 @@ impl ListNode { T: std::hash::Hash + Eq + Copy + Clone, { let mut hashmap = HashMap::new(); - if let Some(node) = linked_list { - let mut current = Some(node.clone()); - while let Some(cur) = current { - let borrow = cur.borrow(); - hashmap.insert(borrow.val.clone(), cur.clone()); - current = borrow.next.clone(); - } + let mut node = linked_list; + + while let Some(cur) = node { + let borrow = cur.borrow(); + hashmap.insert(borrow.val.clone(), cur.clone()); + node = borrow.next.clone(); } + hashmap } } diff --git a/codes/rust/include/tree_node.rs b/codes/rust/include/tree_node.rs index fb9d11464..3cb37cfc5 100644 --- a/codes/rust/include/tree_node.rs +++ b/codes/rust/include/tree_node.rs @@ -72,23 +72,21 @@ pub fn vec_to_tree(arr: Vec>) -> Option>> { } /* 将二叉树序列化为列表:递归 */ -fn tree_to_vec_dfs(root: Option>>, i: usize, res: &mut Vec>) { - if root.is_none() { - return; +fn tree_to_vec_dfs(root: Option<&Rc>>, i: usize, res: &mut Vec>) { + if let Some(root) = root { + // i + 1 is the minimum valid size to access index i + while res.len() < i + 1 { + res.push(None); + } + res[i] = Some(root.borrow().val); + tree_to_vec_dfs(root.borrow().left.as_ref(), 2 * i + 1, res); + tree_to_vec_dfs(root.borrow().right.as_ref(), 2 * i + 2, res); } - let root = root.unwrap(); - // i + 1 is the minimum valid size to access index i - while res.len() < i + 1 { - res.push(None); - } - res[i] = Some(root.borrow().val); - tree_to_vec_dfs(root.borrow().left.clone(), 2 * i + 1, res); - tree_to_vec_dfs(root.borrow().right.clone(), 2 * i + 2, res); } /* 将二叉树序列化为列表 */ pub fn tree_to_vec(root: Option>>) -> Vec> { let mut res = vec![]; - tree_to_vec_dfs(root, 0, &mut res); + tree_to_vec_dfs(root.as_ref(), 0, &mut res); res }