思路源自
【力扣hot100】【LeetCode 25】k个一组翻转链表|虚拟节点的应用
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummyHead = new ListNode(0, head);
ListNode cur = dummyHead;
while (true) {
ListNode groupPre = cur;
int kth = k;
while (cur != null && kth > 0) {
cur=cur.next;
kth--;
}
if (cur == null) {
break;
} else {
ListNode groupNext = cur.next;
cur = groupPre.next;
ListNode pre = groupNext;
while (cur != groupNext) {
ListNode temp = cur.next;
cur.next = pre;
pre=cur;
cur = temp;
}
cur = groupPre.next;
groupPre.next = pre;
}
}
return dummyHead.next;
}
}