Given the head of a singly linked list and an integer k, reverse the nodes k at a time and
return the modified list. If the number of nodes isn’t a multiple of k, leave the final group
as-is. Must be done in-place, without modifying node values.
(LeetCode 25)
Input: head = [1, 2, 3, 4, 5], k = 2Output: [2, 1, 4, 3, 5]
Input: head = [1, 2, 3, 4, 5], k = 3Output: [3, 2, 1, 4, 5]Approach: break the logic into 3 parts — find the kth node from the current position, reverse that group, then connect it back to the list and continue. Helper methods keep it modular.
class Solution { public ListNode reverseKGroup(ListNode head, int k) { // Handle edge cases if (head == null || k == 1) return head;
// Pointers to track current node and previous group's tail ListNode temp = head; ListNode prevGroupTail = null;
// New head after the first reversal ListNode newHead = null;
// Traverse the entire list while (temp != null) { // Step 1: Find the kth node from current temp ListNode kth = getKthNode(temp, k); if (kth == null) { // Less than k nodes left, connect the last group if needed if (prevGroupTail != null) { prevGroupTail.next = temp; } break; }
// Store the next group's starting node ListNode nextGroupHead = kth.next;
// Step 2: Detach and reverse the current group kth.next = null; ListNode reversedGroupHead = reverseList(temp);
// Step 3: Connect previous group to current reversed group if (prevGroupTail != null) { prevGroupTail.next = reversedGroupHead; } else { newHead = reversedGroupHead; // Set new head on first reversal }
// Move prevGroupTail to current group's tail (which is temp now) prevGroupTail = temp;
// Move temp to the start of the next group temp = nextGroupHead; }
// In case we never reversed anything (i.e., total nodes < k) return newHead != null ? newHead : head; }
// Helper to get the kth node from current private ListNode getKthNode(ListNode node, int k) { while (node != null && k > 1) { node = node.next; k--; } return node; }
// Helper to reverse a linked list (standard 3-pointer method) private ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head;
while (curr != null) { ListNode front = curr.next; curr.next = prev; prev = curr; curr = front; }
return prev; }}Walkthrough: traverse the list with temp; for each group, find the kth node ahead via
getKthNode (if fewer than k nodes remain, leave them unreversed), detach and reverse the group,
then connect the previous group’s tail to the newly reversed group. Repeat to the end.
Time: O(n) — each node is visited once during traversal and once during reversal. Space: O(1) — no extra data structures, reversal is done in-place.