Currently working on a problem where I reverse a linked list. I was able to successfully write it but I feel like I may have an invalid number of mutable and immutable references. Rubberducking here by explaining what I think is happening but let me know in more detail!
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
type WrappedNode = Option<Box<ListNode>>;
impl Solution {
pub fn reverse_list(head: WrappedNode) -> WrappedNode {
let mut next = head;
let mut prev: WrappedNode = None;
while let Some(mut current) = next { // 1
next = current.next; // 2
current.next = prev; // 3
prev = Some(current); // 4
}
prev
}
}
I have marked the important lines above.
// 1: I am moving the wrapped box of "next" into the variable "current" in the scoped within the loop. This is not a copy if my understanding is correct but a move.
//2: I am moving current.next to next (which is currently invalid?) thus invalidating current.next
//3: I am moving prev to current.next (which is currently invalid?) thus invalidating prev
//4: ??? Why can I now move the value from current- I thought i just invalidated one of its fields by moving