ReverseKGroup { public ListNode reverseKGroup(ListNode<Integer> head, int k) { if (k == 1 || head == null || head.next == null) { return head; } ListNode<Integer> newHead = new ListNode(0, head); ListNode<Integer> insertBefore = newHead; ListNode<Integer> current = head; while (current != null) { int i = 0; while (current != null && i < k) { current = current.next; i++; } if (i == k) { ListNode<Integer> last = insertBefore.next; ListNode<Integer> r = insertBefore.next.next; insertBefore.next.next = current; while (r != current) { ListNode<Integer> rn = r.next; r.next = insertBefore.next; insertBefore.next = r; r = rn; } insertBefore = last; } } return newHead.next; }  ListNode reverseKGroup(ListNode<Integer> head, int k);  }
@Test(dataProvider = "reverseLinkedList") public void testReverseKGroup(ListNode<Integer> ln, int k, ListNode<Integer> expected) { TestUtilities.assertEquals(new ReverseKGroup().reverseKGroup(ln, k), expected); }