[英]What would be a better way to implement .pop() in my single linked list in Rust?
我已經在 Rust 中實現了我自己的單鏈表版本,這是我學習它的挑戰之一,除了 .pop() 方法之外,我對那里的所有東西都很滿意。 使用 2 while 循環非常丑陋且效率低下,但我發現沒有其他方法可以克服將索引處的節點 len() - 2 設置為 None(彈出列表),並使用來自索引處的節點的數據的問題len() - 1 表示 Some(data) 返回值(返回被彈出的元素)。
pub struct SimpleLinkedList<T> {
head: Option<Box<Node<T>>>,
}
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
impl<T> Default for SimpleLinkedList<T> {
fn default() -> Self {
SimpleLinkedList { head: None }
}
}
impl<T: Copy> Clone for SimpleLinkedList<T> {
fn clone(&self) -> SimpleLinkedList<T> {
let mut out: SimpleLinkedList<T> = SimpleLinkedList::new();
let mut cur = &self.head;
while let Some(node) = cur {
cur = &node.next;
out.push(node.data)
}
out
}
}
impl<T> SimpleLinkedList<T> {
pub fn new() -> Self {
Default::default()
}
pub fn len(&self) -> usize {
let mut c = 0;
let mut cur = &self.head;
while let Some(node) = cur {
cur = &node.next;
c += 1;
}
c
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn push(&mut self, _element: T) {
let mut cur = &mut self.head;
match cur {
Some(_) => {
while let Some(node) = cur {
cur = &mut node.next;
}
}
None => (),
}
*cur = Some(Box::from(Node {
data: _element,
next: None,
}));
}
pub fn pop(&mut self) -> Option<T>
where
T: Copy,
{
let length = &self.len();
let mut cur = &mut self.head;
let mut out = None;
match cur {
Some(_) if *length > 1usize => {
let mut c = 0usize;
while let Some(node) = cur {
cur = &mut node.next;
if c >= length - 1 {
out = Some(node.data);
break;
}
c += 1;
}
c = 0usize;
cur = &mut self.head;
while let Some(node) = cur {
cur = &mut node.next;
if c == length - 2 {
break;
}
c += 1;
}
}
Some(node) => out = Some(node.data),
None => (),
}
*cur = None;
out
}
pub fn peek(&self) -> Option<&T> {
let cur = &self.head;
match cur {
Some(node) => Some(&node.data),
None => None,
}
}
}
impl<T: Copy> SimpleLinkedList<T> {
pub fn rev(&self) -> SimpleLinkedList<T> {
let mut clone = self.clone();
let mut out: SimpleLinkedList<T> = SimpleLinkedList::new();
while let Some(val) = clone.pop() {
out.push(val)
}
out
}
}
impl<'a, T: Copy> From<&'a [T]> for SimpleLinkedList<T> {
fn from(_item: &[T]) -> Self {
let mut out: SimpleLinkedList<T> = SimpleLinkedList::new();
for &e in _item.iter() {
out.push(e);
}
out
}
}
impl<T> Into<Vec<T>> for SimpleLinkedList<T> {
fn into(self) -> Vec<T> {
let mut out: Vec<T> = Vec::new();
let mut cur = self.head;
while let Some(node) = cur {
cur = node.next;
out.push(node.data)
}
out
}
}
你可以通過跟蹤你看到的最后一個元素來避免重新遍歷列表(然后在最后更新它)。
如果你對如何做到這一點很天真,你就會遇到麻煩; 您的“前一個”指針保留列表其余部分的所有權,借用檢查器不允許這樣做。 訣竅是在您進行時斷開該鏈接 - 為此您可以使用mem::replace
函數。 完成此操作后,您必須將其放回原處,以免再次失去對先前節點的跟蹤。
以下是完整的內容(您必須原諒我對unwrap
自由使用 - 我確實認為它使事情更清晰):
pub fn pop(&mut self) -> Option<T>
where T : Copy,
{
use std::mem::replace;
let curr = replace(&mut self.head, None);
if curr.is_none() { // list started off empty; nothing to pop
return None;
}
let mut curr = curr.unwrap(); // safe because of the check above
if let None = curr.next { // popped the last element
return Some(curr.data);
}
let mut prev_next = &mut self.head;
while curr.next.is_some() {
// Take ownership of the next element
let nnext = replace(&mut curr.next, None).unwrap();
// Update the previous element's "next" field
*prev_next = Some(curr);
// Progress to the next element
curr = nnext;
// Progress our pointer to the previous element's "next" field
prev_next = &mut prev_next.as_mut().unwrap().next;
}
return Some(curr.data);
}
順便說一句,如果您願意稍微更改接口以便我們每次都返回一個“新”列表(在pop
函數中獲得所有權),或者使用持久數據結構,那么所有這些指針混洗都會簡化很多,因為它們在學習 Rust 中使用太多的鏈表(已經在評論中提到):
pub fn pop_replace(self) -> (Option<T>, Self) {
// freely mutate self and all the nodes
}
你會使用像:
let elem, list = list.pop();
fn pop(&mut self) -> Option<T> {
let mut current: &mut Option<Box<Node<T>>> = &mut self.head;
loop {
// println!("curr: {:?}", current);
match current {
None => {
return None;
}
Some(node) if node.next.is_none() => {
let val = node.data;
*current = node.next.take();
return Some(val);
}
Some(ref mut node) => {
current = &mut node.next;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.