File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
src/main/java/com/geekidentity/leetcode/n0025 Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .geekidentity .leetcode .n0025 ;
2
+
3
+ public class ReverseKGroup {
4
+ public ListNode reverseKGroup (ListNode head , int k ) {
5
+ if (head == null || head .next == null ) return head ;
6
+ ListNode dummy = new ListNode (0 , head );
7
+ ListNode pre = dummy , end = dummy ;
8
+ while (end .next != null ) {
9
+ for (int i = 0 ; i < k && end != null ; i ++) {
10
+ end = end .next ;
11
+ }
12
+ if (end == null ) break ;;
13
+ ListNode start = pre .next ;
14
+ ListNode next = end .next ;
15
+ end .next = null ;
16
+ ListNode newHead = reverse (start );
17
+ pre .next = newHead ;
18
+ start .next = next ;
19
+ pre = start ;
20
+ end = pre ;
21
+ }
22
+ return dummy .next ;
23
+
24
+ }
25
+
26
+ public ListNode reverse (ListNode head ) {
27
+ if (head == null || head .next == null ) return head ;
28
+ ListNode pre = null , cur = head , next = null ;
29
+ while (cur != null ) {
30
+ next = cur .next ;
31
+ cur .next = pre ;
32
+ pre = cur ;
33
+ cur = next ;
34
+ }
35
+ return pre ;
36
+ }
37
+
38
+ static class ListNode {
39
+ int val ;
40
+ ListNode next ;
41
+ ListNode () {}
42
+ ListNode (int val ) { this .val = val ; }
43
+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments