题解 | #链表中的节点每k个一组翻转#
其实就是题目翻转链表的k个节点连续执行多次,每次都更换头结点。
import java.util.*;
public class Solution {
public ListNode reverseKGroup (ListNode head, int k) {
if (head == null || head.next == null || k == 1) return head;
int len = 0;
ListNode temp = head;
while (temp != null) {
temp = temp.next;
len++;
}
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode pre = newHead;
for (int j = k ; j <= len; j += k) {
ListNode cur = newHead.next;
for (int i = 1; i <= k; i++) {
ListNode curNext = cur.next;
cur.next = newHead.next;
newHead.next = cur;
cur = curNext;
}
head.next = cur;
newHead = head;
head = cur;
}
return pre.next;
}
}