题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
public class Solution {
public ListNode reverseKGroup (ListNode head, int k) {
if (head == null || head.next == null) return head;
if (k <= 1) return head;
ListNode left = new ListNode(-1);
left.next = head;
ListNode pre = left;
while (pre != null) {
pre = reverse_next_k(pre, k);
}
return left.next;
}
/**
* 翻转前k个元素,不足k个则保持原样
* 返回本次翻转的k个元素呆的最有一个元素,作为下一次翻转的头部,方便采用前插
*/
public static ListNode reverse_next_k(ListNode head, int k) {
ListNode right = head.next;
for (int i = 1; i <= k; i++) {
// 不足k个则直接返回头部
if (right == null) return null;
right = right.next;
}
ListNode cur = head.next;
while (cur.next != right) {
ListNode next = cur.next;
cur.next = next.next;
next.next = head.next;
head.next = next;
}
return cur;
}
}


