/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
// 区间 [a, b) 包含 k 个待反转元素
ListNode a = head;
ListNode b = head;
for (int i = 0; i < k; i++) {
// 不足 k 个,不需要反转,base case
if (b == null) {
return head;
}
b = b.next;
}
// 反转前 k 个元素
ListNode newHead = reverse(a, b);
// 递归反转后续链表并连接起来
a.next = reverseKGroup(b, k);
return newHead;
}
private ListNode reverse(ListNode a, ListNode b) {
ListNode pre = null;
ListNode cur = a;
// while 终止的条件改一下就行了
while (cur != b) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
// 返回反转后的头结点
return pre;
}