题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d4cca501950aed5a4fcebbe34c8c61a9.png)
分析
- 判断是否为k长链表
- 单节点处理
- k长链表反转
- 链接前后链表
代码
import java.util.*;
public class Solution {
public ListNode reverseKGroup (ListNode head, int k) {
if (head == null || head.next == null || !isKn(head, k)) {
return head;
}
ListNode start = head;
int i = k;
ListNode pre = null;
ListNode temp = null;
while (k > 0 ) {
k--;
temp = head.next;
head.next = pre;
pre = head;
head = temp;
if (k == 0 && head != null) {
start.next = reverseKGroup(head, i);
}
if (head == null) {
break;
}
}
return pre;
}
public boolean isKn(ListNode head, int k) {
ListNode knCheck = head;
int kn = k;
while (knCheck != null && kn > 0) {
knCheck = knCheck.next;
kn--;
}
if (kn != 0) {
return false;
}
return true;
}
}