public static ListNode reverse(ListNode a) {
ListNode pre,cur,next;
pre = null;
cur = a;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
// 反转[a,b)个节点
public static ListNode reverse(ListNode a, ListNode b) {
ListNode pre,cur,next;
pre = null;
cur = a;
while(cur!=b){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
这和 K个一组翻转链表反转 有啥子关系呢?
每K个一组就是相当于区间【a,b)之间的节点有K个,然后一一反转。
这就用到了递归
public static ListNode reverseKGroup(ListNode head, int k) {
if(head == null) return head;
// 区间 [a, b) 包含 k 个待反转元素
ListNode a = head;
ListNode b = head;
for (int i = 0; i < k; i++) {
// 不足 k 个,不需要反转
if(b == null) return head;
b = b.next;
}
// 反转前 k 个元素,并获得反转后的头节点
ListNode newNode = reverse(a, b);
// 递归反转后续链表并连接起来,这里a反转后由子节点中由头变为尾,所以和a.next拼接
a.next = reverseKGroup(b, k);
return newNode;
}