解题思路:
通过循环开始分组,每一组进行一次逆转,通过start和end保存链表开始逆转和结束逆转的位置。当完成当前组的逆转以后,更新strat和end的位置,进行下一组逆转
注意的几个点:
1、注意数组边界问题,在我的代码中,对end在每组的更新中,更新了一次,同时每次循环也会更新一次,如果end本来就为空,两次next以后,显然end是空指针为报错
2、注意找清楚对strat和end的更新和恢复,这是循环能否继续下去的关键。
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if(head==null){
return null;
}
ListNode listNode=new ListNode(-1);
listNode.next=head;
ListNode start=listNode;
ListNode end=listNode;
int i=0;
while(end!=null){
if(i==k){
i=1;
//截取片段
ListNode log=start;
ListNode node=start.next;
ListNode cut=end.next;
start.next=null;
end.next=null;
//逆转拼接
ListNode reverse=ReverseList(node);
log.next=reverse;
ListNode sd=reverse;
while (sd.next!=null){
sd=sd.next;
}
sd.next=cut;
//恢复现场
start=sd;
end=sd.next;
//判断是否越界,防止两次.next出现空指针
if (end==null){
break;
}
}
i++;
end=end.next;
}
return listNode.next;
}
public static ListNode ReverseList(ListNode head) {
if (head==null){
return null;
}
ListNode a=new ListNode(head.val);
while(head.next!=null){
head=head.next;
ListNode listNode=new ListNode(head.val);
listNode.next=a;
a=listNode;
}
return a;
}
}