Skip to content

Commit 3a7b737

Browse files
committed
add 92
1 parent 875147a commit 3a7b737

File tree

3 files changed

+114
-0
lines changed

3 files changed

+114
-0
lines changed

S0092-reverse-linked-list-ii/Cargo.lock

Lines changed: 55 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "S0092-reverse-linked-list-ii"
3+
version = "0.1.0"
4+
authors = ["xargin <cao1988228@163.com>"]
5+
edition = "2018"
6+
7+
[dependencies]
8+
leetcode_prelude="^0.1"
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use leetcode_prelude::*;
2+
fn main() {
3+
let l = linkedlist![1,2,3,4,5];
4+
let x = Solution::reverse_between(l, 2,4);
5+
println!("{:?}", x);
6+
}
7+
8+
// 本质上还是遍历了 1.x 遍
9+
// 好像没有办法像其它语言那样记录多个指针?
10+
struct Solution;
11+
impl Solution {
12+
pub fn reverse_between(mut head: Option<Box<ListNode>>, m: i32, n: i32) -> Option<Box<ListNode>> {
13+
if head.is_none() {
14+
return head
15+
}
16+
let mut cur = &mut head;
17+
let mut cur_idx = 1;
18+
while cur_idx != m {
19+
cur_idx += 1;
20+
cur = &mut cur.as_mut().unwrap().next;
21+
}
22+
23+
let mut prev = None;
24+
while cur_idx <= n {
25+
cur_idx += 1;
26+
// swap(prev, next)
27+
// prev == next
28+
std::mem::swap(&mut cur.as_mut().unwrap().next, &mut prev);
29+
// swap(prev, cur
30+
std::mem::swap(&mut prev, &mut cur);
31+
}
32+
33+
let tail = std::mem::replace(cur, None);
34+
35+
// connect mid and tail
36+
let mut mid_cur = &mut prev;
37+
while mid_cur.is_some() {
38+
mid_cur = &mut mid_cur.as_mut().unwrap().next;
39+
}
40+
std::mem::replace(mid_cur, tail);
41+
42+
// connect head and mid
43+
let mut head_cur = &mut head;
44+
while head_cur.is_some() {
45+
head_cur = &mut head_cur.as_mut().unwrap().next;
46+
}
47+
std::mem::replace(head_cur, prev);
48+
49+
head
50+
}
51+
}

0 commit comments

Comments
 (0)