File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments