← All problems

25. Reverse Nodes in K Group

HardOpen on LeetCodeProblem statement

Problem Statement

25. Reverse Nodes in k-Group

Hard


Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

 

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

 

Constraints:

 

Follow-up: Can you solve the problem in O(1) extra memory space?

Java

Source file
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode curr = head, kHead = curr, prev = null, dummy = new ListNode(0);
        ListNode[] newChain = null, lastChain = new ListNode[] { dummy, dummy };
        while (curr != null) {
            kHead = curr;
            int i = 0;
            while (curr != null && i < k) {
                prev = curr;
                curr = curr.next;
                i++;
            }
            if (i == k) {
                prev.next = null; // disconnect next chain
                newChain = reverseLL(kHead); // returns {head, tail} after reversal
                lastChain[1].next = newChain[0]; // connect lastChain tail -> newChain head
                lastChain = newChain;
            } else
                lastChain[1].next = kHead; // connect without reversal of remnants
        }
        return dummy.next;
    }

    /** Reverse a LinkedList
    * @return ListNode[]{head, tail}
    */
    private ListNode[] reverseLL(ListNode head) {
        ListNode prev = null, curr = head;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        return new ListNode[] { prev, head }; // {newHead, newTail}
    }
}