
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.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
8 if not head or k == 1:
9 return head
10
11 dummy = ListNode(0)
12 dummy.next = head
13 prev, current = dummy, head
14
15 length = 0
16 while current:
17 length += 1
18 current = current.next
19
20 while length >= k:
21 current = prev.next
22 next = current.next
23 for i in range(1, k):
24 current.next = next.next
25 next.next = prev.next
26 prev.next = next
27 next = current.next
28 prev = current
29 length -= k
30
31 return dummy.next
32The solution constructs a dummy node linked to the head, simplifying edge operations. Counting list length allows determination of how many full k-reversals are possible. Nodes in these groups are then reversed using iterative swaps of pointers.
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.