Skip to content

Commit 8b6c0eb

Browse files
Merge pull request #2943 from master-of-none/problem25
Create: 0025-reverse-nodes-in-k-group.rs
2 parents c1c8133 + b4f85b9 commit 8b6c0eb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Diff for: rust/0025-reverse-nodes-in-k-group.rs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
impl Solution {
2+
pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
3+
let mut dummy = Some(Box::new(ListNode {next: head, val: 0 }));
4+
let mut cur = dummy.as_mut();
5+
6+
'outer: loop {
7+
let mut start = cur.as_mut().unwrap().next.take();
8+
if start.is_none() {
9+
break 'outer;
10+
}
11+
12+
let mut end = start.as_mut();
13+
for _ in 0..(k - 1) {
14+
end = end.unwrap().next.as_mut();
15+
16+
if end.is_none() {
17+
cur.as_mut().unwrap().next = start;
18+
break 'outer;
19+
}
20+
}
21+
22+
let mut tail = end.as_mut().unwrap().next.take();
23+
let end = Solution::reverse(start, tail);
24+
cur.as_mut().unwrap().next = end;
25+
26+
for _ in 0..k {
27+
cur = cur.unwrap().next.as_mut()
28+
}
29+
}
30+
dummy.unwrap().next
31+
}
32+
33+
fn reverse(
34+
mut head: Option<Box<ListNode>>,
35+
tail: Option<Box<ListNode>>,
36+
) -> Option<Box<ListNode>> {
37+
let mut prev = tail;
38+
let mut cur = head;
39+
40+
while let Some(mut cur_node) = cur {
41+
let mut next = cur_node.next.take();
42+
cur_node.next = prev.take();
43+
prev = Some(cur_node);
44+
cur = next
45+
}
46+
prev
47+
}
48+
}

0 commit comments

Comments
 (0)