题解 | #牛群的重新分组#
牛群的重新分组
https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode curr = head;
int count = 0;
while (curr != null) {
count++;
if (count % k == 0) {
prev = reverse(prev, curr.next);
curr = prev.next;
} else {
curr = curr.next;
}
}
return dummy.next;
}
ListNode reverse(ListNode prev, ListNode end) {
ListNode curr = prev.next;
ListNode tail = curr;
while (curr != end) {
ListNode temp = curr.next;
curr.next = prev.next;
prev.next = curr;
curr = temp;
}
tail.next = end;
return tail;
}
}
解题思路分析:构造虚拟头结点为初始prev,初始curr指向head。用count++计数,不能整除k就curr后移一位,能整除就带入函数操作,再更新prev和curr指针;写了一个反转两个节点的函数。

