From 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb Mon Sep 17 00:00:00 2001 From: Orangerot Date: Thu, 27 Jun 2024 11:30:16 +0200 Subject: Initial commit --- reverse-linked-list-ii/src/main.rs | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 reverse-linked-list-ii/src/main.rs (limited to 'reverse-linked-list-ii/src/main.rs') diff --git a/reverse-linked-list-ii/src/main.rs b/reverse-linked-list-ii/src/main.rs new file mode 100644 index 0000000..20790aa --- /dev/null +++ b/reverse-linked-list-ii/src/main.rs @@ -0,0 +1,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> +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { + next: None, + val + } + } +} + +impl ListNode { + fn new_from_vec(val: Vec) -> Option> { + 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 { + 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>, left: i32, right: i32) -> Option> { + let v = &mut head.unwrap().to_vec(); + v[((left-1) as usize)..(right as usize)].reverse(); + + ListNode::new_from_vec( v.to_vec() ) + } +} -- cgit v1.2.3