题目:
分析:
这题主要考察链表的反转,我们需要一个链表反转的函数fz(),需要讲解的可以查看我之前的博客,主函数我们需要把整条链切成n个k个结点的链表(最后一个可能不是),然后对每个小链表进行反转,并记录下他们的头尾节点方便将各个小链表之间串联起来。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int i=k;
ListNode l1=head;
ListNode l2=null;
ListNode l3=null;
ListNode l4=null;
ListNode l5=null;
while(l1!=null) {
l2 = l1;
while (i != 1 && l1 != null) {
l1 = l1.next;
i--;
}
if (l1 != null) {
l3 = l1.next;
fz(l2, l1);
if(l5==null){
l5=l1;
}else{
l4.next=l1;
}
l4=l2;
l1 = l3;
i = k;
}else{
l4.next=l2;
}
}
return l5;
}
public void fz(ListNode head,ListNode last){
ListNode l1=null;
ListNode l2=null;
while(head!=last){
l1=head.next;
head.next=l2;
l2=head;
head=l1;
}
head.next=l2;
return ;
}
}