using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { int groups = GetLongth(head) / k; if (groups == 0 || k == 1) return head; ListNode pre = null; ListNode cur = head; ListNode nex; ListNode pf = null;//上一组的第一个 ListNode pl;//这一组的第一个 ListNode newHead = null; for (int i = 0; i < groups; i++) { pl = cur; pre = cur; cur = cur.next; for (int j = 1; j < k; j++) { nex = cur.next; cur.next = pre; pre = cur; cur = nex; } pl.next = cur; if (pf != null) pf.next = pre; pf = pl; newHead = newHead == null ? pre : newHead; } return newHead; } public int GetLongth(ListNode head) { int length = 0; while (head != null) { head = head.next; length++; } return length; } }