implement a list using Rust
Posted cutepig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了implement a list using Rust相关的知识,希望对你有一定的参考价值。
Rust果然比較複雜,在經歷了n次compile fail,終于寫成了一個 list
難點: 對Rc<>的用法不熟悉。對borrow checker不夠熟悉
有些寫法可能還不是最短的
use std::rc::Rc; fn main() println!("Hello, world!"); let li = ListInternal data: 1, next: None, ; let li = ListInternal data: 2, next: Some(Rc::new(li)), ; let mut l = List next: Some(li) ; for i in 1..10 l.push_back(i); l.print(); struct ListInternal data: i32, next: Option<Rc<ListInternal>>, struct List next: Option<ListInternal>, impl ListInternal fn print(&self) println!("", self.data); if let Some(ref v) = self.next v.print(); fn print_loop(&self) let mut t = self; loop println!("", t.data); if let Some(ref v) = t.next t = v; else break; fn last(&mut self) -> &mut Self let mut t = self; loop if let Some(ref mut v) = t.next t = Rc::get_mut(v).unwrap(); else break; t impl List fn new() -> List List next: None fn print(&self) if let Some(ref v) = self.next v.print_loop(); fn push_back(&mut self, data: i32) let li = ListInternal data: data, next: None, ; if let Some(ref mut v) = self.next v.last().next = Some(Rc::new(li)); else self.next = Some(li);
以上是关于implement a list using Rust的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 225Implement Stack using Queues
LeetCode Implement Queue using Stacks
[LeetCode]Implement Stack using Queues
232. Implement Queue using Stacks