我希望使用 Rust 解决一道力扣问题 (删除链表的倒数第 N 个节点)。我的解法使用两个指针来找到需要移除的 Node
:
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
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<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
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编写。如果我想将一个不可变引用变为可变的,我该怎么做?如果不行,有没有其他方式实现相同的逻辑,同时让借用检查器满意呢?
RefCell
。 - Peter Hall