1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
use crate::List::*;
enum List { Cons(u32, Box<List>), Nil, }
impl List { fn new() -> List { Nil }
fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) }
fn len(&self) -> u32 { match *self { Cons(u32,ref tail) => 1 + tail.len(), Nil => 0 } }
fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { format!("{}, {}", head, tail.stringify()) }, Nil => { format!("Nil") }, } } }
fn main() { let mut list = List::new();
list = list.prepend(1); list = list.prepend(2); list = list.prepend(3);
println!("链表的长度是: {}", list.len()); println!("{}", list.stringify()); }
|