0

I'm trying to solve problem 61 on leetcode using rust. And I implemented the code as below and it works fine

#[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 }
    }
}

pub fn rotate_right(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
    match head {
        Some(mut head) => {
            let mut p = &mut head;

            let mut n = 1;
            while p.next.is_some() {
                p = p.next.as_mut().unwrap();
                n += 1;
            }

            let k = k % n;
            p = &mut head;
            for _ in 0..(n - k - 1) {
                p = p.next.as_mut().unwrap();
            }

            if p.next.is_none() {
                return Some(head);
            }

            let mut q = p.next.take().unwrap();
            p = &mut q;

            while p.next.is_some() {
                p = p.next.as_mut().unwrap();
            }
            p.next = Some(head);

            // while let Some(next) = &mut p.next {
            //     p = next;
            // }
            // p.next = Some(head);
            // `p.next`: cannot assign to `p.next` because it is borrowed

            Some(q)
        }
        None => None,
    }
}

I know it's ok to take ownership, like this

while p.next.is_some() {
    p = p.next.as_mut().unwrap();
}
p.next = Some(head);

But why is the &mut not released here?

while let Some(next) = &mut p.next {
    p = next;
}
p.next = Some(head);

The &mut of p.next was taken by next in Some(next). But seems it to be released?

tony
  • 47
  • 1
  • 4

0 Answers0