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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
struct ListNode *pleft,*pmid,*pright,*plast,*pnew,*new_head;
int i;
if(head==NULL||head->next==NULL||k==1)
return head;
pnew=head;
for(i=1;i<=k-1;i++) //寻找第k个结点,并设为头节点
{
pnew=pnew->next;
if(pnew==NULL)
return head;
}
new_head=pnew; //第k个为头节点
pleft=head; //left
pmid=head->next; //mid
plast=head;
while(pmid!=NULL)
{
pright=pmid->next; //pright
pmid->next=pleft; //mid指向left
if(pmid==pnew) //如果mid是第k个节点
{
pmid=pright; //pmid变成pright
pnew=pmid; //pnew从当前开始算
plast->next=pnew; //在判断是否还有k个时,先将plast指向当前这个
if(pnew==NULL) //如果后面已经全为空了,那么可以直接输出了
return new_head;
for(i=1;i<=k-1;i++) //否则就继续寻找第k个
{
pnew=pnew->next;
if(pnew==NULL) //如果出现空,则直接返回,不用逆序
return new_head;
}
//若有k个,则plast指向第k个
plast->next=pnew; //plast一定是指向它
plast=pmid; //重置plast
continue;
}
pleft=pmid;
pmid=pright;
}
return new_head;
}