/* * File: list_node.rs * Created Time: 2023-03-05 * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug)] pub struct ListNode { pub val: T, pub next: Option>>>, } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } /* Generate a linked list with an array */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> where T: Copy + Clone, { let mut head = None; // insert in reverse order for item in array.iter().rev() { let node = Rc::new(RefCell::new(ListNode { val: *item, next: head.clone(), })); head = Some(node); } head } /* Generate a hashmap with a linked_list */ pub fn linked_list_to_hashmap( linked_list: Option>>>, ) -> HashMap>>> 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 } }