straightforward java solution

  • 0


    public ListNode reverseKGroup(ListNode head, int k) {
        int len = count(head);
        return helper(head,len,k);
    public ListNode helper(ListNode head, int len, int k){
        if (len<k) return head;
        int i = 0;
        ListNode cur = head, prev = null, next = null;
        while (i<k){
            next =;
   = prev;
            prev = cur;
            cur = next;
        } = helper(cur,len-k,k);
        return prev;
    public int count(ListNode head){
        int res = 0;
        ListNode cur = head;
        while (cur != null){
            cur =;
        return res;

    Count the num of nodes in the linked list first to decide whether we should do the reversing job.
    If condition is satisfied, go do the reverse in the helper function and the make it recursive.

    The basic idea is quite similar to this problem:

Log in to reply

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