Rust链表push_sort函数

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

我正在尝试用 Rust 实现我自己的 Linkedlist(出于学习目的)。

我使用的结构:

struct Node<T> {
    value: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Node<T> {
    pub fn new(val: T) -> Self {
        return Node {
            value: val,
            next: None,
        };
    }

    pub fn new_with_next(val: T, next: Option<Box<Node<T>>>) -> Self {
        return Node {
            value: val,
            next: next,
        };
    }
}

struct List<T> {
    head: Option<Box<Node<T>>>,
}

我已经实现了一个函数,可以将项目推送到排序列表中的正确位置(我们假设是这样)。它工作得很好(经过长时间的努力),但作为一个 rust 初学者,并且因为 rust 看起来与我使用的其他语言非常不同,我想知道是否有更惯用的方法在 Rust 中实现这一点。

    fn push_sort(&mut self, val: T) where T: std::cmp::PartialOrd {
        match &mut self.head {
            Some(head) => {
                if head.value >= val {
                    self.head = Some(Box::new(Node::new_with_next(val, self.head.take())));
                    return;
                }
            },
            None => {
                self.head = Some(Box::new(Node::new(val)));
                return;
            }
        };

        let mut current = &mut self.head;
        while let Some(node) = current {
            if node.next.is_none() {
                node.next = Some(Box::new(Node::new(val)));
                return;
            }

            if val < node.next.as_ref().unwrap().value {
                node.next = Some(Box::new(Node::new_with_next(val, node.next.take())));
                return;
            }

            current = &mut node.next;
        }
    }
rust linked-list
1个回答
0
投票

您不需要

match
while let
,它们都可以在单个循环中完成,与检查循环中的节点是否为
Some
None
及其条件相同:

    fn push_sort(&mut self, val: T)
    where
        T: std::cmp::PartialOrd,
    {
        let mut current = &mut self.head;
        while let Some(c) = current {
            if c.value >= val {
                let old = std::mem::replace(c, Box::new(Node::new(val)));
                c.next = Some(old);
                return;
            }
            current = &mut c.next;
        }
        *current = Some(Box::new(Node::new(val)));
    }
© www.soinside.com 2019 - 2024. All rights reserved.