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 = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
            i++;
        }
        head.next = helper(cur,len-k,k);
        return prev;
    }
    
    public int count(ListNode head){
        int res = 0;
        ListNode cur = head;
        while (cur != null){
            res++;
            cur = cur.next;
        }
        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:http://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/


Log in to reply
 

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