forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
41 lines (41 loc) · 1.13 KB
/
Solution.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
// 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 reverse_between(
head: Option<Box<ListNode>>,
left: i32,
right: i32
) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode { val: 0, next: head }));
let mut pre = &mut dummy;
for _ in 1..left {
pre = &mut pre.as_mut().unwrap().next;
}
let mut cur = pre.as_mut().unwrap().next.take();
for _ in 0..right - left + 1 {
let mut next = cur.as_mut().unwrap().next.take();
cur.as_mut().unwrap().next = pre.as_mut().unwrap().next.take();
pre.as_mut().unwrap().next = cur.take();
cur = next;
}
for _ in 0..right - left + 1 {
pre = &mut pre.as_mut().unwrap().next;
}
pre.as_mut().unwrap().next = cur;
dummy.unwrap().next
}
}