25. K个一组翻转链表
这题有点难啊啊啊啊,怎么会有人能这样想到,这也太聪明了吧啊啊啊
题目:


题解:
java
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k <= 1) return head;
// Step 1: 创建虚拟头节点
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy; // prev 始终指向当前组的前一个节点
// Step 2: 计算链表总长度(可选,也可以在每轮检查 k 个节点)
int length = 0;
ListNode cur = head;
while (cur != null) {
length++;
cur = cur.next;
}
// Step 3: 处理 fullGroups = length / k 个完整组
int fullGroups = length / k;
for (int i = 0; i < fullGroups; i++) {
// start 是当前组的第一个节点
ListNode start = prev.next;
// then 是 start 的下一个,即将被"头插"的节点
ListNode then = start.next;
// 执行 k-1 次头插操作
for (int j = 0; j < k - 1; j++) {
// 1. start 跳过 then,连到 then 的下一个
start.next = then.next;
// 2. then 插到 prev 后面
then.next = prev.next;
prev.next = then;
// 3. then 移动到下一个待处理节点
then = start.next;
}
// 一轮反转结束,prev 移动到本组的最后一个节点(即原来的 start)
prev = start;
}
return dummy.next;
}
}