Java 1ms beats 100%


  • 0
    C

    Reverse the first k nodes, then use recursion to reverse the rest nodes.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || head.next == null) return head;
            if(k == 1) return head;
            
            int count = countNode(head);
            if(count < k) return head;
    
            // reverse the first k nodes
            ListNode newHead = null;
            ListNode cur = head;
            for(int i = 0; i < k; i++){
                ListNode temp = cur.next;
                cur.next = newHead;
                newHead = cur;
                cur = temp;
            }
    
            head.next = reverseKGroup(cur, k);
            return newHead;
            
        }
        public int countNode(ListNode head){
            int count = 0;
            ListNode cur = head;
            while(cur != null){
                count++;
                cur = cur.next;
            }
            return count;
        }
    }
    

Log in to reply
 

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