Java Solution


  • 0
    S
    class Solution {
        
        ListNode reverse(ListNode head) {
            if (head == null || head.next == null) {
                return head; 
            }
            ListNode curr = head, next = head.next, temp = null;
            while (next != null) {
                temp = next.next;
                next.next = curr; 
                curr = next;
                next = temp;
            }
            head.next = null;
            return curr; 
        }
        
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || head.next == null || k < 2) {
                return head; 
            }
            ListNode curr = head, newHead = null, currHead = head, prevTail = null; 
            int i = 1;
            while (curr != null) {
                // Traverse the list for a given length k 
                while (i < k && curr != null) {
                    curr = curr.next;
                    i++;
                }
                
                // If we end up having a k less than the list length return. 
                if (curr == null) {
                    return (newHead == null) ? currHead : newHead;
                }
                
                // Split the list at the current node. 
                ListNode nextListHead = curr.next; 
                curr.next = null;
                
                // Reverse the list from curr head till current node. 
                ListNode reversedIter = reverse(currHead); 
                if (newHead == null) {
                    newHead = reversedIter;
                } 
                
                // Attach the reversed list to the prev list's tail. 
                if (prevTail != null) {
                    prevTail.next = reversedIter;
                }
                
                // Attach the current reversed list to the next list. 
                while (reversedIter.next != null) {
                    reversedIter = reversedIter.next; 
                }
                reversedIter.next = nextListHead;
                
                // Repeat the process for the next list. 
                currHead = nextListHead;
                prevTail = reversedIter; 
                curr = nextListHead;
                i = 1;
            }
            return newHead; 
        }
    }
    

Log in to reply
 

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