首页 > 解决方案 > 如何实现递归节点结构?

问题描述

来自 Python,我想在 Rust 中实现一个 Node 结构,类似于下面的 Python 代码:

class Node:
    def __init__(self, value: int, next_node: "Node"):
        self.value: int = value
        self.next: Node = next_node

    def __repr__(self):
        return f"Node(value: {self.value}, next: {self.next})"

if __name__ == "__main__":
    a = Node(1, None)
    b = Node(2, None)

    # Link a.next with b
    a.next = b

    print(f"a now: {a}\n")
    # Prints:
    # a now: Node(value: 1, next: Node(value: 2, next: None))

    # Change .value inside b
    b.value = 3

    print(f"a now: {a}")
    print(f"b now: {b}\n")
    # Prints:
    # a now: Node(value: 1, next: Node(value: 3, next: None))
    # b now: Node(value: 3, next: None)

    # Change .value inside a.next
    a.next.value = 4

    print(f"a now: {a}")
    print(f"b now: {b}")
    # Prints:
    # a now: Node(value: 1, next: Node(value: 4, next: None))
    # b now: Node(value: 4, next: None)

到目前为止,我在 Rust 中的实现如下:

#[derive(Debug)]
#[derive(Clone)]
struct Node {
    value: i32,
    next: Option<Box<Node>>,
}

fn main() {
    let mut a = Node { value: 1, next: None };
    let mut b = Node { value: 2, next: None };

    // Box and encapsulate a and b inside Option
    let mut option_a = Some(Box::new(a));
    let mut option_b = Some(Box::new(b));

    // Link a.next with b
    if let Some(ref mut a_unwrapped) = option_a {
        a_unwrapped.next = option_b;
    }
    println!("a now: {:?}", option_a);
    // Prints:
    // a now: Some(Node { value: 1, next: Some(Node { value: 2, next: None }) })
}

但是,该行将a_unwrapped.next = option_b;节点的option_b内部移动a.next而不是创建引用。现在我已经无法访问了option_b

与上述无关,可能可以使用以下方法更改节点内的值:

if let Some(ref mut b_unwrapped) = option_b {
    b_unwrapped.value = 3;
    // It is desired that a.next.value is now 3 as well
}

我想实现这个,因为我想在不使用 Rust 的数据结构和不使用关键字的情况下创建一个Queue数据结构(可能还有二叉树),这只是个人挑战。Vecunsafe

到目前为止,我能够使用此处Stack描述的链表方法构建数据结构。

如您所见,我很难理解如何实现这一点。

在我看来,在 Rust 中拥有多个指向同一个对象的引用相当困难(因为数据竞争和竞争条件),或者我只是使用了错误的方法。

标签: rust

解决方案


推荐阅读