↻one more pass.
Linked lists · Hard

Reverse Nodes In K Group: the idea to remember.

Reverse each complete group of k linked list nodes, leaving a final incomplete group unchanged.

Solve on LeetCode ↗

The core insight

First locate the kth node of a group, then reverse exactly that group and reconnect its two boundaries.

Why it works

Checking group length before reversal preserves the required order of an incomplete tail.

The mistake to avoid

Reconnect the old group head as the new tail and advance from it, not from the new head.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

ListNode reverseKGroup(ListNode head, int k) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode before = dummy;
    while (true) {
        ListNode last = before;
        for (int i = 0; i < k && last != null; i++) last = last.next;
        if (last == null) return dummy.next; // Leave an incomplete group unchanged.
        ListNode after = last.next, current = before.next, previous = after;
        while (current != after) {
            ListNode next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        ListNode oldHead = before.next;
        before.next = last;
        before = oldHead; // The former head is now the group's tail.
    }
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.