class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode end = dummy; while(end.next != null){ for(int i = 0; i < k && end != null; i++){ end = end.next; } if(end == null){ break; } ListNode next = end.next; ListNode start = pre.next; end.next = null;//将k段分出去以后需要在后面添上一个null已断开连接 pre.next = reverse(start); start.next = next; pre = start; end = start; } return dummy.next; } public static ListNode reverse(ListNode start){ ListNode pre = null; ListNode cur = start; while(cur != null){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
来源:https://www.cnblogs.com/zhaijiayu/p/11521275.html