题目链接
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode newHead=new ListNode(1);
ListNode result=newHead;
ListNode pointer=head;
while(pointer!=null)
{
ListNode end=pointer;
for(int i=1;i<k&&end!=null;i++)
{
end=end.next;
}
if(end==null)
{
newHead.next=pointer;
break;
}
ListNode nextPoin=end.next;
end.next=null;
newHead.next=reverse(pointer);
newHead=pointer;
pointer=nextPoin;
}
return result.next;
}
public ListNode reverse(ListNode toReverse)
{
ListNode result=null;
while(toReverse!=null)
{
ListNode temp=toReverse.next;
toReverse.next=result;
result=toReverse;
toReverse=temp;
}
return result;
}
}