I'm new on Rust, i'm just doing some exercise. There is a linked list. For example, 0->1->2->3->4, cut it off at index 2, then reverse both, and then compose them. => 0<-1<-2 3<-4 => 2->1->0->4->3
#[derive(debug)]
struct Node{
val: usize,
next: Option<Box<Node>>,
}
impl Node {
fn new(i: usize) -> Node {
...
}
fn reverse_at(self, k: usize) -> Box<Node> {
let mut prev = None;
let mut curr = Box::new(self);
let first_part_tail = &mut curr;
let mut i: usize = 0;
while i <= k {
let next = curr.next.take();
curr.next = prev;
match next {
Some(next_node) => {
prev = Some(curr);
curr = next_node;
}
None => return curr,
}
i += 1;
}
let head = prev.unwrap();
prev = None;
loop {
let next = curr.next.take();
curr.next = prev;
match next {
Some(next_node) => {
prev = Some(curr);
curr = next_node;
}
None => {
first_part_tail.next = Some(curr);
return head;
}
}
}
}
}
I need to get the mutable borrow of the first node0, and set 0.next=4 after getting the last node4 at the end of function. But node0's ownership is already been send to node1.
Obviously, error[E0499]: cannot borrow `curr.next` as mutable more than once at a time
happens, i don't know what to do. This stuck me for a long time. Any help please.
&
, i suppose this function would change the Node itself. And i don't know how to change self reference into the new node, so i used self
. If someone can modify this, that helps too.
Maybe, change this function to
fn reverse_at(&mut self, k:usize){
...
}
&
before self in your method signature. see: doc.rust-lang.org/1.30.0/book/2018-edition/… – Ultrasaurus&
, i suppose this function would change the Node itself. And i don't know how to change self reference into the new node, so i usedself
. If someone can modify this, that helps too. – IcatreamNode::new(1234)
, this will create a linked list, 4->3->2->1->None.Node::new(1)
will create 1->None. I'll look at the learning resource, thanks. – Icatream