Here is my 1ms answer, but can someone improve it?


  • 0
    E

    mainly idea is treat the list as block and every time check and reverse one block.
    and reverse function will return the last element of the block we reverse last time.

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode index = dummy;
        
        ListNode temp = reverse(dummy, k);
        while (temp != null)
            temp = reverse(temp, k);
        
        return dummy.next;
    }
    
    public ListNode reverse(ListNode pre, int k) {
        ListNode bk = pre;
        if (pre == null) return null;
        ListNode now = pre.next;
        int i = 1;
        while (i <= k && now != null){//check if should do the reverse using count
            i ++;
            now = now.next;
        }
        if (i != k + 1)//check here
            return null;
        
        now = pre.next;
        
        i = 1;
        while (i < k){
            bk = now.next;
            now.next = bk.next;
            bk.next = pre.next;
            pre.next = bk;
            i++;
        }
        
        return now;
    }
    

    but the result shows that this solution is not fast, so could someone give it some improvements?


Log in to reply
 

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