MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/hard/_0025/Solution.java:13–45  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/10/16 desc :

Source from the content-addressed store, hash-verified

11 * </pre>
12 */
13public class Solution {
14 public ListNode reverseKGroup(ListNode head, int k) {
15 if (head == null || k == 1) return head;
16 ListNode node = new ListNode(0), pre = node;
17 node.next = head;
18 for (int i = 1; head != null; ++i) {
19 if (i % k == 0) {
20 pre = reverse(pre, head.next);
21 head = pre.next;
22 } else {
23 head = head.next;
24 }
25 }
26 return node.next;
27 }
28
29 private ListNode reverse(ListNode pre, ListNode next) {
30 ListNode head = pre.next;
31 ListNode move = head.next;
32 while (move != next) {
33 head.next = move.next;
34 move.next = pre.next;
35 pre.next = move;
36 move = head.next;
37 }
38 return head;
39 }
40
41 public static void main(String[] args) {
42 Solution solution = new Solution();
43 ListNode.print(solution.reverseKGroup(ListNode.createTestData("[1,2,3,4,5,6,7,8]"), 3));
44 }
45}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected