
思路
- 先确定能翻转几组
- 每组内进行m到n的反转链表
- 对于反转m到n的问题,确定好循环次数,pre是不动的,循环内:
- 先cur.next = ...
- 再tmp.next = ...
- 再pre.next = ...
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
int size = 0;
ListNode node = head;
while (node != null) {
size++;
node = node.next;
}
int round = size / k;
ListNode pre = dummy;
ListNode cur = dummy.next;
for (int i = 0; i < round; i++) {
for (int j = 1; j < k; j++) {
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
pre = cur;
cur = pre.next;
}
return dummy.next;
}
}