Simple 2 step Java Solution, with comments in code


  • 0
    C

    Here is my solution with simple 2 steps

    1. if we have less then k node in left we return head directly
    2. Else we reverse k node at current level of recursion
      Hope it may help !
        public ListNode reverseKGroup(ListNode head, int k) {
        //1. test weather we have more then k node left, if less then k node left we just return head 
        ListNode node = head;
        int count = 0;
        while (count < k) { 
            if(node == null)return head;
            node = node.next;
            count++;
        }
        // 2.reverse k node at current level 
           ListNode pre = reverseKGroup(node, k); //pre node point to the the answer of sub-problem 
            while (count > 0) {  
                ListNode next = head.next; 
                head.next = pre; 
                pre = head; 
                head = next;
                count = count - 1;
            }
            return pre;
          }
    

Log in to reply
 

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