方法一:模拟
这道题可以进行拆解,拆解成对每个部分进行反转链表,而只需要确定pre、start、end、next这几个位置。
在进行反转时要断开pre到start的指针、end到next的指针,然后对start到end部分进行反转,之后再将pre指向反转后的头节点,start的next指向next,重新建立起连接。
pre移动到start、end也移动到start。
/**
* 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 dummyNode = new ListNode();
dummyNode.next = head;
ListNode start, pre = dummyNode, end = dummyNode;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) end = end.next;
if (end == null) break;
start = pre.next;
pre.next = null;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return dummyNode.next;
}
public ListNode reverse(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}