mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-24 10:33:34 +08:00
zig : upgrade codes && rust : add codes for chapter_searching and chapter_dynamic_programming. (#591)
* zig : update zig codes * rust : add codes for linear_search and hashing_search * rust : add codes for linear_search and hashing_search * rust : add codes for chapter_dynamic_programming
This commit is contained in:
@@ -6,7 +6,9 @@
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ListNode<T> {
|
||||
pub val: T,
|
||||
pub next: Option<Rc<RefCell<ListNode<T>>>>,
|
||||
@@ -19,4 +21,41 @@ impl<T> ListNode<T> {
|
||||
next: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/* Generate a linked list with an array */
|
||||
pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>>
|
||||
where
|
||||
T: Copy + Clone,
|
||||
{
|
||||
let mut head = None;
|
||||
let mut prev = None;
|
||||
for item in array.iter().rev() {
|
||||
let node = Rc::new(RefCell::new(ListNode {
|
||||
val: *item,
|
||||
next: prev.take(),
|
||||
}));
|
||||
prev = Some(node.clone());
|
||||
head = Some(node);
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
/* Generate a hashmap with a linked_list */
|
||||
pub fn linked_list_to_hashmap(
|
||||
linked_list: Option<Rc<RefCell<ListNode<T>>>>,
|
||||
) -> HashMap<T, Rc<RefCell<ListNode<T>>>>
|
||||
where
|
||||
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();
|
||||
}
|
||||
}
|
||||
hashmap
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user