1- package class04 ;
2-
3- // 测试链接:https://leetcode.com/problems/reverse-nodes-in-k-group/
4- public class Code04_ReverseNodesInKGroup {
5-
6- // 不要提交这个类
7- public static class ListNode {
8- public int val ;
9- public ListNode next ;
10- }
11-
12- public static ListNode reverseKGroup (ListNode head , int k ) {
13- ListNode start = head ;
14- ListNode end = getKGroupEnd (start , k );
15- if (end == null ) {
16- return head ;
17- }
18- // 第一组凑齐了!
19- head = end ;
20- reverse (start , end );
21- // 上一组的结尾节点
22- ListNode lastEnd = start ;
23- while (lastEnd .next != null ) {
24- start = lastEnd .next ;
25- end = getKGroupEnd (start , k );
26- if (end == null ) {
27- return head ;
28- }
29- reverse (start , end );
30- lastEnd .next = end ;
31- lastEnd = start ;
32- }
33- return head ;
34- }
35-
36- public static ListNode getKGroupEnd (ListNode start , int k ) {
37- while (--k != 0 && start != null ) {
38- start = start .next ;
39- }
40- return start ;
41- }
42-
43- public static void reverse (ListNode start , ListNode end ) {
44- end = end .next ;
45- ListNode pre = null ;
46- ListNode cur = start ;
47- ListNode next = null ;
48- while (cur != end ) {
49- next = cur .next ;
50- cur .next = pre ;
51- pre = cur ;
52- cur = next ;
53- }
54- start .next = end ;
55- }
56-
57- }
1+
2+
3+ package class04 ;
4+
5+ // 测试链接:https://leetcode.com/problems/reverse-nodes-in-k-group/
6+ public class Code04_ReverseNodesInKGroup {
7+
8+ // 不要提交这个类
9+ public static class ListNode {
10+ public int val ;
11+ public ListNode next ;
12+ }
13+
14+ public static ListNode reverseKGroup (ListNode head , int k ) {
15+ ListNode start = head ;
16+ ListNode end = getKGroupEnd (start , k );
17+ if (end == null ) {
18+ return head ;
19+ }
20+ // 第一组凑齐了!
21+ head = end ;
22+ reverse (start , end );
23+ // 上一组的结尾节点
24+ ListNode lastEnd = start ;
25+ while (lastEnd .next != null ) {
26+ start = lastEnd .next ;
27+ end = getKGroupEnd (start , k );
28+ if (end == null ) {
29+ return head ;
30+ }
31+ reverse (start , end );
32+ lastEnd .next = end ;
33+ lastEnd = start ;
34+ }
35+ return head ;
36+ }
37+
38+ public static ListNode getKGroupEnd (ListNode start , int k ) {
39+ while (--k != 0 && start != null ) {
40+ start = start .next ;
41+ }
42+ return start ;
43+ }
44+
45+ public static void reverse (ListNode start , ListNode end ) {
46+ end = end .next ;
47+ ListNode pre = null ;
48+ ListNode cur = start ;
49+ ListNode next = null ;
50+ while (cur != end ) {
51+ next = cur .next ;
52+ cur .next = pre ;
53+ pre = cur ;
54+ cur = next ;
55+ }
56+ start .next = end ;
57+ }
58+
59+ }
0 commit comments