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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM