gpt4 book ai didi

list - 如何从链表的末尾删除第 N 个节点?

转载 作者:行者123 更新时间:2023-11-29 08:09:18 27 4
gpt4 key购买 nike

这是我用来表示单个链表的数据结构:

type Link = Option<Box<Node>>;

pub struct Node {
elem: i32,
next: Link,
}

我想实现一个方法来从列表末尾删除第 N 个节点:

// Original list
A -> B -> C -> D -> None

// remove 1 from the end of the original list
A -> B -> C -> None

// Remove 2 from the end of the original list
A -> B -> D -> None

我一直在和借阅检查员打架:

fn remove_nth_node_from_end(list: &mut Link, n: usize) {
if list.is_none() {
return;
}
let mut i = 0;
let mut fast = list;
while let Some(ref mut node) = {fast} {
if i == n {
break;
}
i += 1;
fast = &mut node.next;
}

// issues start here, since I need to mutably borrow
// the list (and it has already been moved above for fast)
// but without moving I have troubles implementing the above loop
let mut slow = &mut list;
// iterate over the list using slow and fast
// when fast is None
// slow.next = slow.next.next
}
error[E0596]: cannot borrow immutable argument `list` as mutable
--> src/lib.rs:25:25
|
25 | let mut slow = &mut list;
| ^^^^ cannot borrow mutably
help: consider removing the `&mut`, as it is an immutable binding to a mutable reference
|
25 | let mut slow = list;
| ^^^^

error[E0382]: use of moved value: `list`
--> src/lib.rs:25:25
|
13 | let mut fast = list;
| -------- value moved here
...
25 | let mut slow = &mut list;
| ^^^^ value used here after move
|
= note: move occurs because `list` has type `&mut std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait

如何实现该方法的剩余部分?

请注意,我的方法没有将 self 作为参数,并且列表参数至少需要在当前实现中移动两次。

最佳答案

这是不使用递归就可以编写方法的方法。

fn remove_nth(list: &mut Link, n: usize) {
if list.is_none() {
return;
}
let get_length = |l: &Link| {
let mut length = 0;
let mut current = l;
while let Some(n) = {current} {
length += 1;
current = &n.next;
}
length
};
let length = get_length(list);
let mut i = 0;
let mut current = list;
while i < length - n {
if let Some(link) = {current} {
current = &mut link.next;
} else {
panic!("Invalid node!");
}
i += 1;
}
*current = current.as_mut().unwrap().next.take();
}

不幸的是,我没能通过使用更高效的运行者模式来取悦借用检查员。

关于list - 如何从链表的末尾删除第 N 个节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com