Rust <7>:数据结构==>链表
1 enum List { 2 Cons(u64, Box<List>), 3 NULL, 4 } 5 6 impl List { 7 fn new() -> List { 8 List::NULL 9 } 10 11 fn prepend(self, elem: u64) -> List { 12 List::Cons(elem, Box::new(self)) 13 } 14 15 fn len(&self) -> u64 { 16 let mut t = self; 17 let mut res = 0u64; 18 while let List::Cons(_, ref next) = *t { 19 res += 1; 20 t = next; 21 } 22 23 res 24 } 25 26 fn stringify(&self) -> String { 27 let mut t = self; 28 let mut res = String::new(); 29 while let List::Cons(r, ref next) = *t { 30 res.push_str(&format!("{}==>", r)); 31 t = next; 32 } 33 34 res.push_str(&format!("NULL")); 35 36 res 37 } 38 } 39 40 fn main() { 41 let mut list = List::new(); 42 43 for x in 0..10000 { 44 list = list.prepend(x); 45 } 46 47 println!("{}", list.stringify()); 48 println!("linked list has length: {}", list.len()); 49 }
HADEX_ FROM HELL.