https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html
#[derive(Debug)]
struct List {
head: Option<Box<List>>,
num: i32,
}
impl List {
fn new() -> List {
List { head: None, num: 0 }
}
fn prepend(self, elem: i32) -> List {
List {
head: Some(Box::new(self)),
num: elem,
}
}
fn len(&self) -> u32 {
match &self.head {
Some(list) => list.len() + 1,
None => 0,
}
}
fn stringify(&self) -> String {
match &self.head {
Some(list) => format!("{}, {}", self.num, list.stringify()),
None => format!("Nil"),
}
}
}
fn main() {
let mut list = List::new();
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}
1
共 3 条评论, 1 页
评论区
写评论里面用到的是递归吗
多谢~
--
👇
rdigua: 加油
too-many-lists
加油
too-many-lists