impl Solution {
// Reverses nodes of a linked list in k-group.
pub fn reverse_k_group(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
// Create a dummy node to simplify edge cases.
let mut dummy = Some(Box::new(ListNode { next: head, val: 0 }));
// 'cur' will be used to traverse the list.
let mut cur = dummy.as_mut();
// Start of the main loop to process the list in chunks of k nodes.
'outer: loop {
// 'start' points to the beginning of the current group.
let mut start = cur.as_mut().unwrap().next.take();
if start.is_none() {
// If 'start' is None, it means we've reached the end of the list.
break 'outer;
}
// 'end' will point to the end of the current group.
let mut end = start.as_mut();
// Iterate k-1 times to reach the end of the group.
for _ in 0..(k - 1) {
end = end.unwrap().next.as_mut();
// If 'end' is None before completing k iterations,
// it means the remaining nodes are less than k and should not be reversed.
if end.is_none() {
cur.as_mut().unwrap().next = start;
break 'outer;
}
}
// 'tail' will point to the node following the current group.
let mut tail = end.as_mut().unwrap().next.take();
// Perform the reversal of the current group.
// Attach the reversed group back to the main list.
cur.as_mut().unwrap().next = Solution::reverse(start, tail);
// Move 'cur' forward by k nodes.
for _ in 0..k {
cur = cur.unwrap().next.as_mut();
}
}
// Return the new list, skipping the dummy node.
dummy.unwrap().next
}
// Helper function to reverse a portion of the list.
fn reverse(
mut head: Option<Box<ListNode>>,
tail: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut prev = tail;
let mut cur = head;
// Standard reverse linked list loop.
while let Some(mut cur_node) = cur {
let mut next = cur_node.next.take();
cur_node.next = prev.take();
prev = Some(cur_node);
cur = next;
}
prev
}
}