作者:浐灞半岛商业_318 | 来源:互联网 | 2022-11-21 02:26
我想解决Rust中的leetcode问题(从列表末尾删除第N个节点).我的解决方案使用两个指针来查找Node
要删除的内容:
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
// two-pointer sliding window
impl Solution {
pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> {
let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head }));
let mut start = dummy_head.as_ref();
let mut end = dummy_head.as_ref();
for _ in 0..n {
end = end.unwrap().next.as_ref();
}
while end.as_ref().unwrap().next.is_some() {
end = end.unwrap().next.as_ref();
start = start.unwrap().next.as_ref();
}
// TODO: fix the borrow problem
// ERROR!
// start.unwrap().next = start.unwrap().next.unwrap().next.take();
dummy_head.unwrap().next
}
}
我借用了链表的两个不可变引用.找到要删除的目标节点后,我想删除一个并使另一个可变.以下每个代码示例都会导致编译器错误:
// ERROR
drop(end);
let next = start.as_mut().unwrap.next.take();
// ERROR
let mut node = *start.unwrap()
我不知道这个解决方案是否可以用Rust编写.如果我可以使不可变引用变为可变,我该怎么做?如果没有,那么无论如何都要实现相同的逻辑,同时让借用检查器满意吗?
1> Shepmaster..:
有没有办法使不可变引用变为可变?
没有.
您可以编写不安全的Rust代码来强制类型排队,但代码实际上是不安全的并导致未定义的行为.你不想要这个.
有关您的具体问题,请参阅:
如何从链表的末尾删除第N个节点?
如何使用两个指针来迭代Rust中的链表?
[Nomicon](https://doc.rust-lang.org/nomicon/transmutes.html)有一个相关的段落,我非常感谢:_"转换和转换为UB;转换为&到&mut总是UB;不,你做不到;不,你不是特别"_