【发布时间】: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->next) 编写验证,如果 current 为 None 这会引发恐慌。
和这里一样
current->next = current->next->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