K个一组反转
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例1: 输入:head = [1,2,3,4,5], k = 2 输出:[2,1,4,3,5] 示例2: 输入:head = [1,2,3,4,5], k = 3 输出:[3,2,1,4,5]
头插法
思路解析
如何控制K个反转并且首尾衔接是关键,采用嵌套循环的方案,外层控制反转次数(len/k),内层控制反转逻辑(k-1)
public static Node reverseKGroup2(Node head, int k) {
Node dummy = new Node(-1);
dummy.next = head;
Node pre = dummy;
Node cur = head;
int len = 0;
while (head != null) {
head = head.next;
len++;
}
for (int i = 0; i < len / k; i++) {
for (int j = 0; j < k - 1; j++) {
Node next = cur.next;
cur.next = cur.next.next;
next.next = pre.next;
pre.next = next;
}
pre = cur;
cur = cur.next;
}
return dummy.next;
}
穿针引线法
思路分析
反转,拼接,移动指针
-
控制五个指针
-
dummy虚拟节点
-
start,end是k组反转的首尾节点
-
pre是start的前一位
-
next是end后一位
-
-
循环将end走到k组反转的尾部,注意判空
-
给start和next定位,注意将end.next = null,否则闭环
-
反转
-
链接,注意链表反转后首尾调换
-
移动,将pre和end链接到start(现在是k组反转的末尾)开启下一轮反转
public static Node reverseKGroup(Node head, int k) {
Node dummy = new Node(-1);
dummy.next = head;
Node pre = dummy;
Node end = dummy;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) {
end = end.next;
}
if (end == null) {
break;
}
Node start = pre.next;
Node next = end.next;
end.next = null;
//反转
reverse(start);
//链接
pre.next = end;
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}