Java 1ms solution


  • 2
    H
     public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k == 1)
            return head;
        return reverseList(head, k);
    }
    public static ListNode reverseList (ListNode node, int k) {
        if (isValidSection(node, k) == false)
            return node;
        ListNode cur = node;
        ListNode prev = null, next = null;
        ListNode temp = cur;
        int count = k;
        while (count > 0) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
            count--;
        }
        temp.next = reverseList(cur, k);
        return prev;
    }
    public static boolean isValidSection(ListNode node, int k) {
        if (node == null)
            return false;
        ListNode cur = node; 
        while (cur != null && k > 0) {
            cur = cur.next;
            k--;
        }
        if (k > 0)
            return false;
        return true;
    }

Log in to reply
 

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