4ms解决方案:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||head.next==null||k==1)
return head;
ListNode p=head;
int countP=0;
while(p!=null&&countP<k){
p=p.next;
countP++;
}
if(countP<k)
return head;//第一个while到这里的语句是在判断长度与K的关系。
ListNode dummy=new ListNode(0);
ListNode prev=head;
ListNode pcur=head.next;
dummy.next=head;
int count=1;
while(count<k){
prev.next=pcur.next;
pcur.next=dummy.next;
dummy.next=pcur;
pcur=prev.next;
count++;
}//链表反转
ListNode temp=reverseKGroup(p,k);//递归截取K长度后剩余的链表。
prev.next=temp;
return dummy.next;
}
}
附上一个反转单链表的文章:反转单链表总结。