The Reverse Nodes in k-Group problem involves reversing nodes of a linked list in groups of size k
. If the number of nodes is not a multiple of k
, the remaining nodes are left as is.
k
k
nodes at the endpublic ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 1) return head;
// Dummy node to simplify edge cases
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prevGroupEnd = dummy;
while (true) {
// Find the kth node
ListNode kth = getKthNode(prevGroupEnd, k);
if (kth == null) break;
// Reverse the group
ListNode groupStart = prevGroupEnd.next;
ListNode nextGroupStart = kth.next;
// Reverse the current group
reverse(groupStart, kth);
// Connect the reversed group
prevGroupEnd.next = kth;
groupStart.next = nextGroupStart;
// Move to the next group
prevGroupEnd = groupStart;
}
return dummy.next;
}
private ListNode getKthNode(ListNode curr, int k) {
while (curr != null && k > 0) {
curr = curr.next;
k--;
}
return curr;
}
private void reverse(ListNode start, ListNode end) {
ListNode prev = null, curr = start, next = null;
while (prev != end) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
}
k
k
nodesInput: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: The nodes are reversed in groups of 2.
k
nodes, single node, empty list