/**
* 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) {
// 构造哑结点,指向最初的head,最后返回值也是通过它获取
ListNode dummy = new ListNode(0, head);
ListNode partPre = dummy;
// slow和fast一开始都指向当前分组的head
ListNode slow = head;
ListNode fast = head;
while (fast != null) {
int nodeNum = 0;
for (; nodeNum < k && fast != null; nodeNum++) {
fast = fast.next;
}
if (nodeNum == k) { // 满足正好K个进入链表局部翻转
ListNode newPartHead = reverseList(slow, fast);
partPre.next = newPartHead; // 上个分组的最后一个元素指向当前头
partPre = slow; // 指向下一个分组头的前一个,即当前分组的最后一个Node
slow = fast; // slow和fast指向相同位置,即下一个分组的头位置
}
}
return dummy.next;
}
// 链表翻转,参见LeetCode206
private ListNode reverseList(ListNode slow, ListNode fast) {
ListNode pre = fast;
ListNode cur = slow;
while (cur != fast) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
10-29
228