一、题目内容
二、题解
解法1:
思路
新建dum节点,用于保存头结点
新建pre和end,用来保存没阶段旋转时的前后节点
注意start节点在反转后,变成了链表的最后一个节点
代码
public ListNode reverseKGroup(ListNode head, int k) {ListNode dum = new ListNode(-1);dum.next = head;ListNode pre = dum, end = dum;while (end.next != null) {for (int i = 0; i < k && end != null; i++) {end = end.next;}if (end == null) {break;}ListNode nextStart = end.next;ListNode start = pre.next;end.next = null;pre.next = reverseList(start);start.next = nextStart;pre = start;end = start;}return dum.next;}private ListNode reverseList(ListNode head) {ListNode pre = null;ListNode cur = head;while (cur != null) {ListNode next = cur.next;cur.next = pre;pre = cur;cur = next;}return pre;}
