-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSoution.rs
48 lines (47 loc) · 1.12 KB
/
Soution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Definition for singly-linked list.
// #[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
// }
// }
// }
impl Solution {
pub fn rotate_right(mut head: Option<Box<ListNode>>, mut k: i32) -> Option<Box<ListNode>> {
if head.is_none() || k == 0 {
return head;
}
let n = {
let mut cur = &head;
let mut res = 0;
while cur.is_some() {
cur = &cur.as_ref().unwrap().next;
res += 1;
}
res
};
k = k % n;
if k == 0 {
return head;
}
let mut cur = &mut head;
for _ in 0..n - k - 1 {
cur = &mut cur.as_mut().unwrap().next;
}
let mut res = cur.as_mut().unwrap().next.take();
cur = &mut res;
while cur.is_some() {
cur = &mut cur.as_mut().unwrap().next;
}
*cur = head.take();
res
}
}