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) { if (head == null || k < 0) { return head; } int len = 0; ListNode temp = head; while (temp != null) { len++; temp = temp.next; } ListNode headNode = new ListNode(-1); headNode.next = head; ListNode tempHeadNode = headNode; ListNode curNode = head; ListNode nextNode = null; for (int i = 0; i < len/k; i++) { for (int j = 1; j < k; j++) { nextNode = curNode.next; curNode.next = nextNode.next; nextNode.next = tempHeadNode.next; tempHeadNode.next = nextNode; } tempHeadNode = curNode; //这样写 也可以curNode = headTempNode.next; curNode = curNode.next; } return headNode.next; } }