题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
断开,反转,链接
public ListNode reverseKGroup (ListNode head, int k) {
ListNode hair=new ListNode(-1);
hair.next=head;
ListNode pre=hair;
ListNode start=null;
ListNode end=null;
ListNode tmp=null;
while(true){
end=pre;
for(int i=0;i<k;i++){//end往后移动k次,从start到end共k个要翻转的节点。不足的话就直接返回链表了。
end=end.next;
if(end==null)return hair.next;
}
tmp=end.next;//挂载end后的节点
end.next=null;//断开链表,下面反转的时候只反转start到end的部分
start=pre.next;
pre.next=reverse(start);//反转完start在最后,end在最前
start.next=tmp;//把链表再连起来
pre=start;//下一轮准备开始
}
}
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode cru=head;
ListNode tmp=null;
while(cru!=null){
tmp=cru.next;
cru.next=pre;
pre=cru;
cru=tmp;
}
return pre;
}