我一直在研究Rust中的单个链接列表。如何实现一种方法,该方法返回对列表中最后一个元素的可变引用,以便追加元素?
我知道Learning Rust With Entirely Too Many Linked Lists,并且对使用不安全的代码也很有信心,但是真的没有安全的实现可以添加元素吗?
当然,不可变的引用很容易实现(get_last_element()
)
use std::mem;
#[derive(Debug)]
pub struct SingleLinkedList {
head: Option<Box<Node>>,
}
#[derive(Debug)]
struct Node {
data: u32,
next: Option<Box<Node>>,
}
impl SingleLinkedList {
fn new() -> Self {
SingleLinkedList { head: None }
}
fn get_last_element(&self) -> Option<&Box<Node>> {
match self.head {
Some(ref el) => {
let mut iterator = el;
loop {
match iterator.next {
Some(ref next_el) => {
iterator = next_el;
}
None => return Some(iterator),
}
}
}
None => return None,
}
}
fn push_front(&mut self, _data: u32) {
let new_head = Some(Box::new(Node {
data: _data,
next: mem::replace(&mut self.head, None),
}));
self.head = new_head;
}
}
fn main() {
let mut list = SingleLinkedList::new();
list.push_front(1);
list.push_front(2);
let ptr = list.get_last_element();
println!("PTR: {:?}", ptr);
println!("{:?}", list);
}