思路
分解任务,先找到这k个一组的链表数据,保证start指向第一个要翻转的数据,end指向最后一个要翻转的数据,提前记录好这k个一组的前一个节点和后一个节点,也就是整体的pre和next,翻转之后pre指向翻转后返回头节点,初始的头start指向整体的next,最后接着维护pre和end
代码
class Solution {
ListNode reverse(ListNode head){
// 翻转head链表
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while(end.next != null){
for(int i = 0; i < k && end != null; i++) end = end.next;
if(end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
// 该组前序,链接上该组
pre.next = reverse(start);
// 该组的链接后面链表
start.next = next;
pre = start;
end = start;
}
return dummy.next;
}
}