/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// try to find k+1th node, if cannot find, return head
// otherwise, reverse first k nodes, recursively do the rest
ListNode cur = head;
int count = 0;
while (cur != null && count != k){
cur = cur.next;
count++;
}
if (count == k){
cur = reverseKGroup(cur, k);
while (count-- > 0){
ListNode temp = head.next;
head.next = cur;
cur = head;
head = temp;
}
head = cur;
}
return head;
}
}