
Sponsored
Sponsored
Use an iterative approach to reverse each group of k nodes separately. This approach leverages an auxiliary dummy node and previous and current pointers to manage the connections at each step. We traverse the list, checking for complete sets of k nodes to reverse them. If a group of nodes has less than k nodes, leave them as they are.
Time Complexity: O(n), where n is the number of nodes in the list, as each node is processed once.
Space Complexity: O(1), since no extra space is used apart from pointers.
1function ListNode(val, next) {
2 this.val = val || 0;
3 this.next = next || null;
4}
5
6var reverseKGroup = function(head, k) {
7 if (!head || k === 1) return head;
8 const dummy = new ListNode(0);
9 dummy.next = head;
10 let prev = dummy, current = head;
11
12 let len = 0;
13 while (current) {
14 len++;
15 current = current.next;
16 }
17
18 while (len >= k) {
19 current = prev.next;
20 let next = current.next;
21 for (let i = 1; i < k; ++i) {
22 current.next = next.next;
23 next.next = prev.next;
24 prev.next = next;
25 next = current.next;
26 }
27 prev = current;
28 len -= k;
29 }
30 return dummy.next;
31};
32JavaScript implementation also adds a dummy node to simplify edge case handling. Calculating list length identifies eligible sections for k-reversals, achieved via stepwise reordering of node links within each suitable group of nodes.
Recurse through the linked list, reversing k nodes at a time. If a full group of k nodes is found, reverse and connect through recursive calls. Terminate when fewer than k nodes are left. This approach inherently uses the call stack for management of reverse sequences.
Time Complexity: O(n), since we process each node once even recursively.
Space Complexity: O(n/k), the recursion depth in worst case equals the number of complete k-sized groups.
1 public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution {
public ListNode ReverseKGroup(ListNode head, int k) {
if (head == null)
return null;
ListNode current = head;
int count = 0;
while (current != null && count < k) {
current = current.next;
count++;
}
if (count == k) {
current = ReverseKGroup(current, k);
while (count-- > 0) {
ListNode tmp = head.next;
head.next = current;
current = head;
head = tmp;
}
head = current;
}
return head;
}
}
The C# solution recursively assesses full k-group potentials, reversing such sequences whilst preserving non-k-alignable endings. Through recursion unwinding, each full group is recursively modified and connected correctly through node pointer modifications.