/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { if(head==NULL||k==1)//先排除特殊情况 return head; int i=0; struct ListNode * f=head; struct ListNode * cur=head; struct ListNode * t=NULL; struct ListNode * last=head; struct ListNode * tou; struct ListNode * result=head; while(f!=NULL)//求出表长,表长为i { f=f->next; i++; } if(k>i)//排除特殊情况 return head; for(int w=0;w<k-1;w++)//找出新链表的头节点 { result=result->next; } for(int m=0;m<k-1;m++)//由纸上画图找规律 { last=last->next; } for(int j=1;j<=i/k;j++)//确定翻转的次数 { if(j!=i/k)//纸上画图找规律 { for(int m=0;m<k;m++) { last=last->next; } } else//画图找规律,最后一次翻转有特殊情况 last=last->next; tou=cur; for(int n=0;n<k;n++)//三指针反转链表,按块翻转(请见三指针迭代法反转链表) { f=cur->next; cur->next=t; t=cur; cur=f; } tou->next=last;//使翻转链表块的尾指针指向下一个翻转链表块的头节点 } return result; } };
本题的难点在于描述last指针的移动规律。画图有助于思考!