# My 2 ms solution using recursion.

• ``````/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null) return head;
ListNode current = head;
int size = 0;
while(current!=null){
size++;
current = current.next;
}
if(k>size) return head;

return helper(head, k);
}

public ListNode helper(ListNode head, int k){
if(head == null) return null;
if(head.next == null || k == 0) return head;
else{
ListNode current = head;
ListNode prev = null;
ListNode next = null;

int count = 0;
if(count + size(head) >=k){
while(count < k && current!=null){
next = current.next;
current.next = prev;
prev = current;
current = next; count++;
}

}else{
return head;
}

if(next!=null) head.next = helper(next,k);

return prev;
}
}

public int size(ListNode head){
ListNode curr = head;
int size = 0;
while(curr!=null){
size++;
curr = curr.next;
}

return size;
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.