Short and elegant Java O(n) time O(1) space solution


  • 1
    G
    public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || k == 0) return head;
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            
            ListNode curr = dummy;
            ListNode tail = curr;
            while(true){
                // To check if there are k nodes remaining
                for(int i = 0;i<k && tail != null;i++){
                    tail = tail.next;
                }
                if(tail == null) break;
                
                ListNode next = curr.next;
                // Putting k-1 nodes before 1st node reverses k nodes
                for(int i=0;i<k-1;i++){
                    ListNode temp = next.next;
                    next.next = temp.next;
                    temp.next = curr.next;
                    curr.next = temp;
                }
                curr = next;
                tail = curr;
            }
            return dummy.next;
        }
    

Log in to reply
 

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