summaryrefslogtreecommitdiff
path: root/reverse-linked-list-ii/src
diff options
context:
space:
mode:
authorOrangerot <purple@orangerot.dev>2024-06-27 11:30:16 +0200
committerOrangerot <purple@orangerot.dev>2024-06-27 11:30:16 +0200
commit4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch)
tree0072cca328fe5adb2ed61004010228ff85e2164d /reverse-linked-list-ii/src
Initial commitHEADmain
Diffstat (limited to 'reverse-linked-list-ii/src')
-rw-r--r--reverse-linked-list-ii/src/main.rs59
1 files changed, 59 insertions, 0 deletions
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<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() )
+ }
+}