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
49
50
51
52
53
54
55
56
57
58
59
|
fn main() {
let tests = [
(vec![1,2,3,4,5], 2, 4, vec![1,4,3,2,5]),
(vec![5], 1, 1, vec![5])
];
for test in tests {
let a = ListNode::new_from_vec(test.0.clone());
println!("{:?} is {:?} should be {:?}", test.0, Solution::reverse_between(a, test.1, test.2).unwrap().to_vec(), test.3);
}
}
#[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 ListNode {
fn new_from_vec(val: Vec<i32>) -> Option<Box<Self>> {
let mut first = ListNode::new(val[0]);
if val.len() > 1 {
let slice = &val[1..val.len()];
first.next = Self::new_from_vec(slice.to_vec());
}
Some(Box::new(first))
}
pub fn to_vec(&self) -> Vec<i32> {
let mut v = Vec::new();
let mut a = Some(Box::new(self.to_owned()));
while a.is_some() {
let t = a.unwrap();
v.push(t.val);
a = t.next;
}
v
}
}
struct Solution {}
impl Solution {
pub fn reverse_between(head: Option<Box<ListNode>>, left: i32, right: i32) -> Option<Box<ListNode>> {
let v = &mut head.unwrap().to_vec();
v[((left-1) as usize)..(right as usize)].reverse();
ListNode::new_from_vec( v.to_vec() )
}
}
|