25. Reverse Nodes in k-Group
Complexity
Space Complexity
Time Complexity
Code
// Helper function to reverse a linked list starting from 'node'
void reverse(ListNode node) {
ListNode previous = null;
while (node != null) {
ListNode nextNode = node.next;
node.next = previous;
previous = node;
node = nextNode;
}
}
public ListNode reverseKGroup(ListNode head, int k) {
// No need to process if k <= 1 or list is empty
if (k <= 1 || head == null) return head;
// Dummy node simplifies edge cases (e.g. reversing at head)
ListNode dummyNode = new ListNode(-1, head);
ListNode prevGroupTail = dummyNode;
ListNode groupStart = head;
while (groupStart != null) {
ListNode groupEnd = groupStart;
int count = k;
// Find the end node of the current group
while (count > 1 && groupEnd != null) {
groupEnd = groupEnd.next;
count--;
}
// If the group is smaller than k, no reversal needed
if (groupEnd == null) break;
// Detach the group and save the remaining list
ListNode nextGroupStart = groupEnd.next;
groupEnd.next = null;
// Reverse the current group
reverse(groupStart);
// Connect the previous group to the new head of this group
prevGroupTail.next = groupEnd;
// Connect the tail of the reversed group to the next part
groupStart.next = nextGroupStart;
// Update pointers for next iteration
prevGroupTail = groupStart;
groupStart = nextGroupStart;
}
return dummyNode.next;
}
Last updated