Java solution with a stack (1ms)


  • -1
    K

    public class Solution {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode[] stack = new ListNode[k];
        ListNode cur = head;
        int i = 0;
        while (i < k && cur != null) {
            stack[i++] = cur;
            cur = cur.next;
        }
        if (i < k) {
            return head;
        }
        head.next = reverseKGroup(cur, k);
        for (i = k - 1; i > 0; i--) {
            stack[i].next = stack[i -1];
        }
        return stack[k - 1];
    }
    

    }


Log in to reply
 

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