7ms simple Java solution(2points+recursive) with complexity: time O(n)/space O(1)


  • 0
    L

    Your runtime beats 80.38% of java submissions.
    81 / 81 test cases passed.
    Status: Accepted
    Runtime: 7 ms

        public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null) return head;
            //Two points - find the kth node. If not find, then return head directly.
            ListNode nextHead = head;
            int i=0;
            while (nextHead!= null && i<k) {
                nextHead = nextHead.next;
                i++;
            }
    
            if(i < k ) {
                return head;
            }
    
            //Reverse the top k nodes
            ListNode forwardHead = new ListNode(0);
            forwardHead.next = head;
            ListNode reverseHead = nextHead, tmp;
    
            while(forwardHead.next != nextHead) {
                tmp = forwardHead.next;
                forwardHead.next = tmp.next;
                tmp.next = reverseHead;
                reverseHead = tmp;
            }
    
            //Recursive call for rest nodes
            head.next = reverseKGroup(nextHead, k);
    
            return reverseHead;
        }
    

Log in to reply
 

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