【问题标题】:Delete duplicated in a linked list solution from C++ to rust从 C++ 到 rust 的链表解决方案中删除重复项
【发布时间】:2022-11-19 04:27:12
【问题描述】:

我有这个用 c++ 编写的代码解决方案来解决问题remove-duplicates-from-sorted-list,现在我正在学习 Rust,我想用 Rust 编程语言构建相同的解决方案我的 Rust linkedList 没有 ListNode 有 Option<Box<Node>>

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return head;

        ListNode* current = head;
        while (current->next) {
            if (current->next->val == current->val)
                current->next = current->next->next;
            else 
                current = current->next;
        }
        return head;
    }
};

我不想改变我解决这个问题的方法,因为任何算法都可以用任何编程语言编写,也许是不同的词,但计算机执行的步骤是相同的​​。

如果不展开 current.unwrap().next,我无法为我的 while (current-&gt;next) 编写验证,如果 current 为 None 这会引发恐慌。

和这里一样 current-&gt;next = current-&gt;next-&gt;next; 我的第一个想法是 current.unwrap().next = current.unwrap().next.unwrap().next;

我尝试阅读有关 Option 和匹配模式的 Rust 文档,以及如何在我的案例中使用 Some while,但我找不到任何类似的示例。

我只能遍历我的 Single linkedList,而无需像这段代码那样修改我的头指针和丢失数据。

    pub fn delete_duplicates(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        if head.is_none() {
            return head
        };
    
        let mut current = &head;
    
        while let Some(node) = current {
            current = &node.next;
        }
        head
    }

如果您知道编写我的 C++ 解决方案的 Rust 方法,请与我分享并感谢您的帮助。

【问题讨论】:

  • 您是否希望它有或没有 C++“解决方案”所展示的内存泄漏?
  • 在 C++ 中,您不需要所有这些,只需使用带有 std::unique 的擦除/删除习惯用法。
  • 内存泄漏对我有好处。因为我知道如何在 C++ 和 Rust 中解决它,另一方面很有趣,但如果你不使用删除,Leetcode 对你的解决方案的排名更好,这没有意义,但却是事实。

标签: c++ data-structures rust linked-list


【解决方案1】:
impl Solution {
    pub fn delete_duplicates(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {

通过匹配而不是仅仅检查 .is_none() 我们可以获得里面的值 并同时检查 None 。

        // if (!head) return head;
        // ListNode* current = head;
        let mut current = match head.as_mut() {
            Some(c) => c,
            None => return head,
        };

然后我们在检查下一个项目时拿走它。 通过使用.take(),我们避免了 2 次可变的电流借用,我们也将以这种方式清理内存。

        // while (current->next) {
        while let Some(mut rest) = current.next.take() {
            // if (current->next->val == current->val)
            if rest.val == current.val {
                // current->next = current->next->next;
                current.next = rest.next;
            } else {
                // since we took earlier we gotta put it back
                current.next = Some(rest);
                // current = current->next;
                // unwrap is perfectly fine since we just set it to Some(rest)
                current = current.next.as_mut().unwrap();
            }
        }
        return head;
    }
}

.as_mut() 只是将 &amp;mut Option&lt;T&gt; 变成 Option&lt;&amp;mut T&gt; 的一种方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多