1、每次从进入函数的头节点优先遍历链表k次,分出一组,若后续不足k个节点,不用反转直接返回头。
2、从进入函数的头节点开始,依次反转接下来的一组链表,反转过程同BM1.反转链表。
3、这一组经过反转后,原来的头变成了尾,后面接下一组的反转结果,下一组采用上述递归继续
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
int i = 0;
//寻找每次翻转的尾部
struct ListNode *tail = head;
//遍历k次到尾部
for(i = 0; i < k; i++)
{
//如果不足k到了链表尾,直接返回,不反转
if(tail == NULL)
return head;
tail = tail->next;
}
struct ListNode *pre = NULL;
struct ListNode *cur = head;
struct ListNode *temp = NULL;
while(cur != tail)
{
temp = cur->next;
cur->next = pre;
//next
pre = cur;
cur = temp;
}
//当前尾指向下一个要反转的链表
head->next = reverseKGroup(tail, k);
return pre;
}