反转链表基本分为三种类型:1.反转整个链表;2.反转前N个节点;3.反转中间第M到第N个节点。(第2种类型可以看作是第3种类型在M=1的一种情况);
k个一组反转其实就是反转中间N个节点的类型;
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode b = head;
for (int i = 0; i < k; i++) {
if (b == null) {
return head;
}
b = b.next;
}
ListNode newHead = reverse(head, b);
head.next = reverseKGroup(b, k);
return newHead;
}
/**
* 反转区间 [a, b) 的元素,注意是左闭右开
* @param a
* @param b
* @return
*/
ListNode reverse(ListNode a, ListNode b) {
ListNode pre,cur,next;
pre = null;
cur = a;
next = a;
while (cur != b) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}