My solution: Two recursions


  • 0
    L
    public class Solution {
    
        public ListNode reverseKGroup(ListNode head, int k) {
            
            //This question can be sovled using recursion
    
            if(head==null||head.next==null) return head;
            
            ListNode p = head;
            int n = 1;
            while(n<k) {
                p = p.next;
                n++;
                if(p==null) return head;
            }
            
            ListNode rest = reverseKGroup(p.next, k);
            p.next = null;
            ListNode front = reverseList(head);
            
            p = front;
            while(p.next!=null) p = p.next;
            p.next = rest;
            
            return front;
        }
         
        
        private ListNode reverseList(ListNode head) {
            
            if(head==null||head.next==null) return head;
            
            ListNode rest = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            
            return rest;
        }
    
    }

Log in to reply
 

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