栈的弹出函数

问题描述 投票:0回答:1

我想实现一个堆栈,但是我在弹出时遇到了很多麻烦。我正在尝试用 while let 循环来做到这一点,但似乎无法击败借用检查器。

pub struct Stack<T>{
    top: Option<Box<Node<T>>>,
}

struct Node<T>{
    val: T,
    under: Option<Box<Node<T>>>,
}

这里是 Stack 实现,这里是 pop:

    pub fn pop(&mut self) -> Option<T>{
        if self.top.is_none(){
            return None;
        }

        let mut last_node = &mut self.top;
        while let Some(node) = last_node{
            if node.under.is_none(){
                break;
            } else{
                last_node = &mut node.under;
            }
        }
        let return_node = std::mem::replace(last_node, None);
        return Some(return_node.unwrap().val);
    }
rust borrow-checker mutable-reference
1个回答
0
投票

这里的技巧是将

top
完全移出
self
,从中取出你需要的东西,然后将
under
放回
self.top

impl<T> Stack<T> {
    pub fn pop(&mut self) -> Option<T> {
        let top = self.top.take(); // take ownership of self.top
        let Some(top) = top else {
            return None
        };

        let Node { val, under } = *top; // we own top so we can move out
        self.top = under; // put the next node down back in self
        Some(val)
    }
}

fn main() {
    // 1 -> 2 -> 3 -> None
    let mut stack = Stack {
        top: Some(
            Node {
                val: 1,
                under: Some(
                    Node {
                        val: 2,
                        under: Some(
                            Node {
                                val: 3,
                                under: None,
                            }
                            .into(),
                        ),
                    }
                    .into(),
                ),
            }
            .into(),
        ),
    };
    println!("{:?}", stack.pop());
    println!("{:?}", stack.pop());
    println!("{:?}", stack.pop());
    println!("{:?}", stack.pop());
    println!("{:?}", stack.pop());
}

结果:

Some(1)
Some(2)
Some(3)
None
None
© www.soinside.com 2019 - 2024. All rights reserved.