Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
24题的扩展。还是递归解决,每次逆置k个节点,若链表当前剩余长度小于k,则直接返回
ListNode* reverseKGroup(ListNode* head, int k) {
int len=0;
ListNode* p=head;
while(p){len++;p=p->next;}
if(k==1 || k>len)return head;
ListNode* p1=head;
ListNode* p2=p1->next;
ListNode* p3=NULL;
if(p2)p3=p2->next;
for(int i=1;i<=k-1;i++){
p2->next=p1;
if(i==k-1)break;
p1=p2;
p2=p3;
if(p3)p3=p3->next;
}
head->next=reverseKGroup(p3,k);
return p2;
}