mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-09 14:06:06 +00:00
feat: add rust codes for linked_list and my_list (#408)
* feat: add rust codes for linked_list * feat: add rust codes for my_list * Update linked_list.rs * Update print_util.rs --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@@ -5,4 +5,6 @@
|
||||
*/
|
||||
|
||||
pub mod print_util;
|
||||
pub mod tree_node;
|
||||
pub mod tree_node;
|
||||
pub mod list_node;
|
||||
pub use list_node::ListNode;
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* File: list_node.rs
|
||||
* Created Time: 2023-03-05
|
||||
* Author: sjinzh (sjinzh@gmail.com)
|
||||
*/
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::cell::RefCell;
|
||||
|
||||
pub struct ListNode<T> {
|
||||
pub val: T,
|
||||
pub next: Option<Rc<RefCell<ListNode<T>>>>,
|
||||
}
|
||||
|
||||
impl<T> ListNode<T> {
|
||||
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
|
||||
Rc::new(RefCell::new(ListNode {
|
||||
val,
|
||||
next: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use std::fmt::Display;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::list_node::ListNode;
|
||||
use crate::tree_node::TreeNode;
|
||||
|
||||
struct Trunk<'a, 'b> {
|
||||
@@ -43,6 +44,15 @@ pub fn print_queue<T: Display>(queue: &VecDeque<T>) {
|
||||
print!("{}{}", data, if i == queue.len() - 1 {"]"} else {", "} );
|
||||
}
|
||||
}
|
||||
|
||||
/* Print a linked list */
|
||||
pub fn print_linked_list<T: Display>(head: &Rc<RefCell<ListNode<T>>>) {
|
||||
print!("{}{}", head.borrow().val, if head.borrow().next.is_none() {"\n"} else {" -> "});
|
||||
if let Some(node) = &head.borrow().next {
|
||||
return print_linked_list(node);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_tree(root: &Rc<RefCell<TreeNode>>) {
|
||||
_print_tree(Some(root), None, false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user