import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { int count = 0; ListNode cur = head; while (cur != null) { count++; cur = cur.next; } if (count < k) { return head; } int term = count / k; ListNode preHead = new ListNode(-1); preHead.next = head; ListNode pre = preHead; ListNode tail; ListNode next; for (int i = 0; i < term; i++) { tail = pre.next; for (int j = 0; j < k - 1; j++) { next = tail.next; tail.next = next.next; next.next = pre.next; pre.next = next; } pre = tail; } return preHead.next; } }