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

  • 0

    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); = head;
        ListNode index = dummy;
        ListNode temp = reverse(dummy, k);
        while (temp != null)
            temp = reverse(temp, k);
    public ListNode reverse(ListNode pre, int k) {
        ListNode bk = pre;
        if (pre == null) return null;
        ListNode now =;
        int i = 1;
        while (i <= k && now != null){//check if should do the reverse using count
            i ++;
            now =;
        if (i != k + 1)//check here
            return null;
        now =;
        i = 1;
        while (i < k){
            bk =;
   = bk;
        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.