题解 | 链表中的节点每k个一组翻转
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ private ListNode reverse(ListNode head, ListNode tail) { ListNode pre = null; ListNode cur = head; while (cur != tail){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre;//此时pre是tail前一个节点。反转区间最后一个,也就是该组反转区间的新头节点 } public ListNode reverseKGroup (ListNode head, int k) { ListNode cur = head; for (int i = 0; i < k; i++) { if (cur == null) return head; cur = cur.next; } //翻转区间的新的头节点 ListNode newhead = reverse(head, cur); head.next = reverseKGroup(cur, k); //连接各组 return newhead; } }