1
votes

I am working on leetcode problem #83 "Remove Duplicates from Sorted List", but I'm stuck on this borrow checker issue.

The ListNode struct is given by the problem so it cannot be changed. I have tried restructuring the loop and if statement, but I haven't found a working solution.

What I am trying to do:

// Definition for singly-linked list.
#[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 }
    }
}

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                continue;
            }
        }
        cursor = &mut c.next;
    }
    list
}

The error I'm getting:

error[E0499]: cannot borrow `*cursor` as mutable more than once at a time
  --> src/lib.rs:17:25
   |
17 |     while let Some(c) = cursor.as_mut() {
   |                         ^^^^^^ mutable borrow starts here in previous iteration of loop

Simplified code that seems to show the same error:

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if c.val > 0 {
            cursor = &mut c.next;
        }
    }
    list
}

I don't understand why the mutable borrow hasn't been dropped before the next iteration of the loop. It seems to be caused by conditionally changing the cursor, but I don't see why that would prevent the borrow from being dropped.

1
Are you working with Rust 2018? With NLL your issue may be fixedAkiner Alkan
@AkinerAlkan Yes I am using the 2018 edition and the latest stable version of Rust (rustc 1.32.0 (9fda7c223 2019-01-16))tlent
You can solve this issue by making the ListNode clonable, Does changing ListNode as clonable is allowed for you?Akiner Alkan
Your main problem is, that you have a continue, without assigning cursor again. But because you are moving it (in your if let statement), you should reassign it.hellow

1 Answers

0
votes

Here's the solution I ended up with. Reassigning cursor in the if statement fixes the problem.

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = list.as_mut();
    while let Some(c) = cursor {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                cursor = Some(c);
                continue;
            }
        }
        cursor = c.next.as_mut();
    }
    list
}