https://leetcode.cn/classic/problems/reverse-nodes-in-k-group public ListNode reverseKGroup (ListNode head, int k) { // 反转前N个 //设置虚拟节点 ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; ListNode cur = head; ListNode tail = head; for(int i = 1;i<=k;i++){ if(tail == null) { //如何长度不足k,直接返回,不反转 return head; } tail = tail.next; } // //设置tail为空 // tail.next = null; //记录 ListNode temp = null; while(cur!=tail){ temp = cur.next; cur.next = pre; pre = cur; cur = temp; } //指向下一段需要翻转链表 head.next = reverseKGroup(tail,k); return pre; }