Intuition
Extract all values into an array, reverse each k-sized chunk in the array, then build a new linked list from the modified array.
Explanation
Brute Force
Traverse the list to collect all values into an array. Then for each complete group of k elements, reverse that segment in the array. Finally, rebuild the linked list from the array.
This is straightforward but uses O(n) extra space for the array and doesn't practice in-place linked list manipulation.
Time is O(n) for traversal, O(n) for chunk reversal, O(n) for rebuilding = O(n) total. Space is O(n) for the array.
Why it's not ideal: it doesn't reverse the list in place and uses extra space proportional to the list length.
Implementation
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode reverseKGroup(ListNode head, int k) {
List<Integer> values = new ArrayList<>();
ListNode node = head;
while (node != null) {
values.add(node.val);
node = node.next;
}
int n = values.size();
for (int i = 0; i + k <= n; i += k) {
int left = i, right = i + k - 1;
while (left < right) {
int temp = values.get(left);
values.set(left, values.get(right));
values.set(right, temp);
left++;
right--;
}
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int v : values) {
current.next = new ListNode(v);
current = current.next;
}
return dummy.next;
}
}