K 个一组翻转链表
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
题解:采取分段式的翻转链表核心点在于翻转,翻转完当前的K个节点后将翻转前尾节点作为下一次翻转的开头,不满足K则直接返回,翻转分为四步,具体流程如图所示。
public class reverseKGroup {
public static ListNode reverseKGroup(ListNode head,int k){
if (head==null||head.next==null){
return head;
}
ListNode tail=head;
for (int i=0;i<k;i++){
if (tail==null){
return head;
}
tail=tail.next;
}
ListNode newhead=reverse(head,tail);
reverseKGroup(tail,k);
return newhead;
}
public static ListNode reverse(ListNode head,ListNode tail){
//指针指向上一个节点,
ListNode pre=null;
//主要作用是用于每次翻转后将head的移动到下一个节点
ListNode next1=null;
while (head!=tail){
//保存head的下一个节点
next1=head.next;
//让head指向pre
head.next=pre;
//pre移动到head
pre=head;
//head移动到保存反转前的next
head=next1;
}
return pre;
}
}