1.翻转链表
三指针 pre cur nxt
ListNode reverse(ListNode head,ListNode tail) { ListNode pre, cur, nxt; pre = null; cur = head; nxt = head; while (cur != tail) { nxt = cur.next; // 逐个结点反转 cur.next = pre; // 更新指针位置 pre = cur; cur = nxt; } // 返回反转后的头结点 return pre;}
2.k个一组递归
递归 + 长度判断 + 左闭右开
- a指向原head,k个一组翻转后变为tail
- b指向tail的下一个节点,也是下一组的head节点
- 链表剩余长度不足k时,不需要翻转,直接返回原head。

ListNode reverseKGroup(ListNode head, int k) { if (head == null) return null; // 区间 [a, b) 包含 k 个待反转元素 ListNode a, b; a = b = head; for (int i = 0; i < k; i++) { // 不足 k 个,不需要反转,base case if (b == null) return head; b = b.next; } // 反转前 k 个元素 ListNode newHead = reverse(a, b); // 递归反转后续链表并连接起来 a.next = reverseKGroup(b, k); return newHead;}