import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
如果头结点为空,或者头结点没有指向下一个节点,直接返回
public class Solution {
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null || head.next == null) {
return head;
}
//创建一个虚拟的节点
ListNode dummy = new ListNode(-1);
//让dummy指向head
dummy.next = head;
//创建两个空指针,指向虚拟节点
ListNode pre = dummy;
ListNode end = dummy;
//while循环判断end.next是否遍历到了最后一个节点,K个节点为一组
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) {
end = end.next;
}
//如果K的值大于剩下的节点数,那就保持不变,跳出循环
if (end == null) {
break;
}
//上述循环走完,end已经走到了反转区域的最后一个节点,用一个指针记录下一个节点的地址
ListNode cur = end.next;
//断掉与end相连的节点
end.next = null;
//创建一个指针用来记录反转区域的第一个节点
ListNode start = pre.next;
//断掉与头节点的连接
pre.next = null;
//将反转区域进行反转,pre.next要与反转后的链表进行连接
pre.next = reverseList(start);
//待反转区域需要把指针及时更新,start.next = cur把尾巴连起来
start.next = cur;
pre = start;
end = start;
}
//最终返回dummy.next
return dummy.next;
}
//采用递归的方式,反转链表
private ListNode reverseList(ListNode head) {
//递归出口,最后cur指向为5,然后返回的head指向为4
if (head == null || head.next == null) {
return head;
}
ListNode cur = reverseList(head.next);
head.next.next = head;
head.next = null;
//cur最终返回到反转区域的第一个节点
return cur;
}
}