Fix rust compile warning and an obvious print error in array.rs (#1144)

* Fix rust compile warning and an obvious print error in array.rs

* Update LinkedList

1. drop unnessaray mut borrow
2. fmt code and make variable more readable

* follow convention of this repo

* Update list_node.rs

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
rongyi 2024-03-18 02:44:03 +08:00 committed by GitHub
parent 7b1094318b
commit 6f1ec66949
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 15 additions and 18 deletions

View file

@ -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);

View file

@ -37,9 +37,10 @@ pub fn access<T>(head: Rc<RefCell<ListNode<T>>>, index: i32) -> Rc<RefCell<ListN
if index <= 0 {
return head;
};
if let Some(node) = &head.borrow_mut().next {
if let Some(node) = &head.borrow().next {
return access(node.clone(), index - 1);
}
return head;
}

View file

@ -45,11 +45,11 @@ struct QuickSortMedian;
impl QuickSortMedian {
/* 选取三个候选元素的中位数 */
fn median_three(nums: &mut [i32], left: usize, mid: usize, right: usize) -> 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

View file

@ -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<T> {
@ -16,10 +16,7 @@ pub struct ListNode<T> {
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode {
val,
next: None,
}))
Rc::new(RefCell::new(ListNode { val, next: None }))
}
/* Generate a linked list with an array */
@ -28,13 +25,12 @@ impl<T> ListNode<T> {
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
@ -45,7 +41,7 @@ impl<T> ListNode<T> {
linked_list: Option<Rc<RefCell<ListNode<T>>>>,
) -> HashMap<T, Rc<RefCell<ListNode<T>>>>
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 {