diff --git a/codes/rust/chapter_array_and_linkedlist/array.rs b/codes/rust/chapter_array_and_linkedlist/array.rs index 090566514..30887fe80 100644 --- a/codes/rust/chapter_array_and_linkedlist/array.rs +++ b/codes/rust/chapter_array_and_linkedlist/array.rs @@ -90,7 +90,7 @@ fn main() { // 长度扩展 let mut nums = extend(nums, 3); print!("将数组长度扩展至 8 ,得到 nums = "); - print_util::print_array(&arr); + print_util::print_array(&nums); // 插入元素 insert(&mut nums, 6, 3); diff --git a/codes/rust/chapter_array_and_linkedlist/linked_list.rs b/codes/rust/chapter_array_and_linkedlist/linked_list.rs index bdb96ec3f..8f054f1c2 100644 --- a/codes/rust/chapter_array_and_linkedlist/linked_list.rs +++ b/codes/rust/chapter_array_and_linkedlist/linked_list.rs @@ -37,9 +37,10 @@ pub fn access(head: Rc>>, index: i32) -> Rc usize { - let (mut l, mut m, mut r) = (nums[left], nums[mid], nums[right]); - if ((l <= m && m <= r) || (r <= m && m <= l)) { + let (l, m, r) = (nums[left], nums[mid], nums[right]); + if (l <= m && m <= r) || (r <= m && m <= l) { return mid; // m 在 l 和 r 之间 } - if ((m <= l && l <= r) || (r <= l && l <= m)) { + if (m <= l && l <= r) || (r <= l && l <= m) { return left; // l 在 m 和 r 之间 } right diff --git a/codes/rust/include/list_node.rs b/codes/rust/include/list_node.rs index 8fc823151..a29b85323 100644 --- a/codes/rust/include/list_node.rs +++ b/codes/rust/include/list_node.rs @@ -1,12 +1,12 @@ /* * File: list_node.rs * Created Time: 2023-03-05 - * Author: codingonion (coderonion@gmail.com) + * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ -use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; +use std::rc::Rc; #[derive(Debug)] pub struct ListNode { @@ -16,25 +16,21 @@ pub struct ListNode { impl ListNode { pub fn new(val: T) -> Rc>> { - Rc::new(RefCell::new(ListNode { - val, - next: None, - })) + Rc::new(RefCell::new(ListNode { val, next: None })) } - + /* Generate a linked list with an array */ - pub fn arr_to_linked_list(array: &[T]) -> Option>>> + pub fn arr_to_linked_list(array: &[T]) -> Option>>> where T: Copy + Clone, { let mut head = None; - let mut prev = None; + // insert in reverse order for item in array.iter().rev() { let node = Rc::new(RefCell::new(ListNode { val: *item, - next: prev.take(), + next: head.clone(), })); - prev = Some(node.clone()); head = Some(node); } head @@ -43,9 +39,9 @@ impl ListNode { /* Generate a hashmap with a linked_list */ pub fn linked_list_to_hashmap( linked_list: Option>>>, - ) -> HashMap>>> + ) -> HashMap>>> where - T: std::hash::Hash + Eq + Copy + Clone + T: std::hash::Hash + Eq + Copy + Clone, { let mut hashmap = HashMap::new(); if let Some(node) = linked_list {